#!/bin/csh -f
#PBS -W group_list=romo
#PBS -A plateval 
#PBS -q romo 
#PBS -l select=ncpus=2
#PBS -l walltime=80:00:00

unset verbose

if ( $?PBS_JOBID ) then
 cd $PBS_O_WORKDIR
else
 set PBS_JOBID = $?
endif

#-----------------------------------------------------------------#

set CTM_2DEMIS = Y   ## Run the 2D / low-level emissions CMAQ to CAMx conversion
set CTM_SEASALT = N  ## Run the seasalt 2D merge
set CTM_PT3DEMIS = Y  ## Run the elevated emissions CMAQ to CAMx conversion
set CTM_PTSMRG = Y ## Merge elevated emissions 

set EMIS_ROOT = /sol/work/ROMO/o3_2014_ria/smoke_out  # Model ready emissions SMOKE out platform root
set INLN_ROOT = /sol/work/ROMO/o3_2014_ria/smoke_out  # Path to SMOKE out inline emissions. May be same as EMIS_ROOT
set SPECIES_MAPPING  = $cwd/ancillary/MAPTBL.CMAQaero6_to_CAMXnewpm_2013aug1

# SECTORLIST 
set SECTORLIST = $cwd/sectorlist_2011ef # Sectorlist
set fire_path = /sol/work/romo/cmaq2camx/scripts/ptfire2011  # Path to CAMx converted ptfire ptsr files

set YEAR = 2011
set datefile = $cwd/ancillary/mergedates_${YEAR}.txt
set execroot = $cwd/bin  # Path to cmaq2camx executables

setenv GRID 12US2
setenv CASE 2011ef_v6_11g   ## primary case name
setenv XORG -2412.
setenv YORG -1620.
setenv NX 396
setenv NY 246
setenv DX 12.
set LAYERS = 25  ## Number of layers to output

set MET = /sol/work/ROMO/met/wrfcamx_v4.0/12US2.TZ0/2011_Kvmin0.1_cloud  # Path to meteorology for seasalt conversion
set LUPATH = /sol/work/ROMO/lrt/camx/$GRID/land  # Path to land use files for seasalt conversion

set start_date = 2010356          #first Julian day
set end_date = 2011365          #last Julian day

#-----------------------------------------------------------------#

set today = $start_date

set QADIR = $cwd/qatemp #location for QA files - domain totals and domain total 2D plots of point emissions
if (! -e $QADIR) then
	mkdir -p $QADIR
endif

set tempdir = $cwd/work  ## Path for the temporary work directory
if (! -e $tempdir) then
	mkdir -p $tempdir
endif

setenv SCRIPTLOG cmaq2camx_${CASE}_${GRID}_${PBS_JOBID}.log  ## Name of script log 
if ( -e $cwd/$SCRIPTLOG) then
	rm $cwd/$SCRIPTLOG
endif

setenv OUTPUT_TIMEZONE 0 ## Timezone for output, typically should be left at 0
setenv OUTPUT_N_LAYERS $LAYERS

## Run the CMAQ to CAMx conversion by loop over the specified date range 
while ($today <= $end_date )

	echo $today >> $cwd/$SCRIPTLOG
	#-----------------------------------------------------------------#
	## Set up date values from Julian date
	set STDATE = $today

	set GDAY = (`$execroot/j2g $today`)
	set YYYY = `echo $GDAY | cut -c1-4`
	set YY = `echo $YYYY | cut -c3-4`
	set MM = `echo $GDAY | cut -c5-6`
	set DD = `echo $GDAY | cut -c7-8`
	set G_DAY = $YYYY$MM$DD
	set GS_DAY = $YY$MM$DD
	set YYDDD = `echo $today | cut -c3-8`

	set iday = `grep ^$STDATE $datefile`
	set dateheader = `grep ^Date $datefile`
	#---------------------------------------------------------------------------#

	## Run the 2D / low-level cmaq to camx conversion
	if ($CTM_2DEMIS == 'Y') then ## 2D emissions preparation
		#need to combine these files, adjust species names, and add duplicate species

		set PATHA = ${EMIS_ROOT}/${CASE}/${GRID}/cmaq_cb05_soa
		set FILEA = emis_mole_all_${G_DAY}_${GRID}_cmaq_cb05_soa_${CASE}.ncf

		if (! -e $PATHA/$FILEA) then
			gunzip -c $PATHA/${FILEA}.gz > ${tempdir}/temp_${PBS_JOBID}.ncf
		else
			cp $PATHA/$FILEA ${tempdir}/temp_${PBS_JOBID}.ncf
		endif

		echo ${PATHA}/${FILEA} >> $cwd/$SCRIPTLOG
		set OUTPATH = ${EMIS_ROOT}/${CASE}/${GRID}/camx
		set OUTFILE = emis2d.$G_DAY.$GRID.$CASE.camx

		if (! -e $OUTPATH) then
			mkdir -p $OUTPATH
		endif

		rm -f ${tempdir}/tmp_emis_${PBS_JOBID}
		## Map the CMAQ species names to CAMx as specified in the MAPTBL
		setenv INFILE  ${tempdir}/temp_${PBS_JOBID}.ncf
		setenv OUTFILE ${tempdir}/tmp_emis_${PBS_JOBID}
		setenv MAPTBL  $SPECIES_MAPPING
		$execroot/spcmap

		setenv CMAQEMIS ${tempdir}/tmp_emis_${PBS_JOBID}
		rm -f ${tempdir}/tmp_pnt_${PBS_JOBID} $OUTPATH/$OUTFILE 

## Convert from low-level cmaq model ready IOAPI 2D file to camx
$execroot/cmaq2uam << EOF
File Type          |EMIS
OutFile1 (IC,BC,AR)|$OUTPATH/$OUTFILE
OutFile2 (TopC,PT) |${tempdir}/tmp_pnt_${PBS_JOBID}
Output Timezone    |$OUTPUT_TIMEZONE
EOF
		rm -f ${tempdir}/tmp_pnt_${PBS_JOBID} ${tempdir}/tmp_emis_${PBS_JOBID}

		rm -f ${tempdir}/qaemis.low.${PBS_JOBID}.in
cat << ieof > ${tempdir}/qaemis.low.${PBS_JOBID}.in
$OUTPATH/$OUTFILE
$QADIR/emis2d.$G_DAY.$GRID.$CASE.camx.tot.txt
$QADIR/emis2d.$G_DAY.$GRID.$CASE.camx.hrs.txt
$QADIR/emis2d.$G_DAY.$GRID.$CASE.camx.pave.bin
ieof

		## Run low-level / 2D QA on camx file
		$execroot/qalowemis < ${tempdir}/qaemis.low.${PBS_JOBID}.in
		rm -f ${tempdir}/qaemis.low.${PBS_JOBID}.in
		rm -f ${tempdir}/temp_${PBS_JOBID}.ncf

		unset OUTFILE
		unsetenv OUTFILE
	endif ## end 2D emissions preparation

	if ($CTM_SEASALT == 'Y') then ## run 2D seasalt merge
		echo "Running seasalt conversion"
		set EMISPATH = ${EMIS_ROOT}/${CASE}/${GRID}/camx

$cwd/seasalt/seasalt.lnx << IEOF
Julian date        :$today
Time zone          :0
Method for open sea:GONG
Method for surfzone:GONG
Coastline length   :NONE
SS lower_limit     :0.0
SS upper limit     :2.5
Output emiss file  :$EMISPATH/seasalt.$today.$GRID.${LAYERS}.wrf_GONG.camx
File identifier    :Sea Salt Emissions
Number of species  :4
Species name # 1   :PCL
Species name # 2   :NA
                   :SS
                   :PSO4
CAMx 3D file       :$MET/met3d.$GS_DAY.$GRID.25.wrf.camx
CAMx 2D file       :$MET/met2d.$GS_DAY.$GRID.25.wrf.camx
CAMx Land Use file :$MET/landuse.$GS_DAY.$GRID.zhang.camx
Saltwater mask     :$LUPATH/oceanmask.$GRID.txt
8 species halo-CH3 :.false.
DOC and CH3I(g)    :1.12e6, 6.55e-4
IEOF

		setenv OUTFILE $EMISPATH/emis2d.$G_DAY.$GRID.${CASE}+ss.camx
		rm -rf $OUTFILE

$cwd/seasalt/mrgspc.lnx << EOF
Input File         |$EMISPATH/emis2d.$G_DAY.$GRID.$CASE.camx
Input File         |$EMISPATH/seasalt.$today.$GRID.${LAYERS}.wrf_GONG.camx
Input File         |END
Output File        |$OUTFILE
EOF
		rm -f $EMISPATH/seasalt.$today.$GRID.${LAYERS}.wrf_GONG.camx 
	endif ## 2D seasalt merge

	## Run the elevated point cmaq inline to camx conversion
	if ($CTM_PT3DEMIS == 'Y') then ## elevated point file preparation
		## Specify the names of the inline sectors to convert from the source apportionment as appears in the sectorlist 
		set sectors = (ptegu ptegu_pk ptnonipm pt_oilgas c3marine othpt) 

		foreach SECTOR ($sectors)

			# Find the representative date based on the date approach from the sectorlist
			set dateappr = `grep ^\"$SECTOR\" $SECTORLIST | cut -d, -f4 | sed 's/"//g'`

			set n = 1
			while ($n <= 9)
				set column = $dateheader[$n]

				if ($dateappr == $column) then
					set repday = $iday[$n]
				endif

				@ n++
			end
		
			# Get the sector-specific case	
			set scase = `grep ^\"$SECTOR\" $SECTORLIST | cut -d, -f2 | sed 's/"//g'`

			set INPATH = ${INLN_ROOT}/${CASE}/$GRID/cmaq_cb05_soa
			set inln = $INPATH/$SECTOR/inln_mole_${SECTOR}_${repday}_${GRID}_cmaq_cb05_soa_${scase}.ncf
			setenv STKGROUP $INPATH/stack_groups_${SECTOR}_${GRID}_${scase}.ncf

			#convert to camx point format and merge into a single point source file and then run qaemis on camx input file
			ls $inln $STKGROUP

			echo $inln >> $cwd/$SCRIPTLOG

			rm -f ${tempdir}/temp_${PBS_JOBID}.ncf

			if (! -e $inln) then
				gunzip -c $inln.gz > ${tempdir}/temp_${PBS_JOBID}.ncf
			else
				cp $inln ${tempdir}/temp_${PBS_JOBID}.ncf
			endif

			rm -f ${tempdir}/tmp_emis_${PBS_JOBID}

			## Map the elevated species
			setenv INFILE  ${tempdir}/temp_${PBS_JOBID}.ncf
			setenv OUTFILE ${tempdir}/tmp_emis_${PBS_JOBID}
			setenv MAPTBL  $SPECIES_MAPPING
			$execroot/spcmap

			rm -f ${tempdir}/temp_${PBS_JOBID}.ncf 

			setenv CMAQEMIS ${tempdir}/tmp_emis_${PBS_JOBID}
			set OUTPATH = ${tempdir}
			set OUTPATH = ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/$SECTOR
			set OUTFILE = ptsr.${SECTOR}.${G_DAY}.${GRID}.bin
			
			mkdir -p $OUTPATH
			rm -f $OUTPATH/$OUTFILE

## Run cmaq inline to camx converter for the inline sector day
$execroot/cmaq2uam << EOF
File Type          |IPNT
OutFile1 (IC,BC,AR)|
OutFile2 (TopC,PT) |$OUTPATH/$OUTFILE
Output Timezone    |$OUTPUT_TIMEZONE
EOF

				rm -f ${tempdir}/tmp_emis_${PBS_JOBID}

				## QA the elevated sector
				rm -f ${tempdir}/qaemis.${SECTOR}.${PBS_JOBID}.in
cat << ieof > ${tempdir}/qaemis.$SECTOR.${PBS_JOBID}.in
$OUTPATH/$OUTFILE
$QADIR/$SECTOR.$G_DAY.$GRID.$CASE.camx.tot.txt
$QADIR/$SECTOR.$G_DAY.$GRID.$CASE.camx.hrs.txt
$QADIR/$SECTOR.$G_DAY.$GRID.$CASE.camx.pave.bin
ieof

			$execroot/qaelev < ${tempdir}/qaemis.$SECTOR.${PBS_JOBID}.in
			rm -f ${tempdir}/qaemis.$SECTOR.${PBS_JOBID}.in

		end ## end loop for conversion of this sector

	endif  ## end point source file processing

	## Run the point sector UAM merge
	if ($CTM_PTSMRG == 'Y') then
		set OUTPATH = ${EMIS_ROOT}/${CASE}/${GRID}/camx
		set OUTFILE = mrgpt.$G_DAY.$GRID.$CASE.camx
		set INPATH = $OUTPATH/sector

		rm -f $OUTPATH/$OUTFILE ${tempdir}/ptsmrg.${PBS_JOBID}.txt

		# Link in ptfire
		rm -f ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/ptfire/ptsr.ptfire.${G_DAY}.${GRID}.bin
		mkdir -p ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/ptfire
		ln -s $fire_path/ptsr.ptfire.${G_DAY}.${GRID}.bin ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/ptfire/ptsr.ptfire.${G_DAY}.${GRID}.bin

		echo "jdate    |$YYDDD" >> ${tempdir}/ptsmrg.${PBS_JOBID}.txt
		echo "emissions|$OUTPATH/$OUTFILE" >> ${tempdir}/ptsmrg.${PBS_JOBID}.txt

		# Set the names of the sectors to be merged and their respective group numbers
		# Use -1 if group numbers are already set in the input file
		set sectors = (ptegu ptegu_pk ptfire ptnonipm pt_oilgas c3marine othpt) 
		set groupnums = (1   2        3      4        5         6        7)

		# Total number of sectors including all subsectors
		set numsect = 7 

		echo "number pt| $numsect" >> ${tempdir}/ptsmrg.${PBS_JOBID}.txt

		set n = 1
		set loopend = `echo $sectors | wc | awk '{print $2}'`
		while ($n <= $loopend)
			set SECTOR = $sectors[$n]
			echo "sat ptsr |${INPATH}/${SECTOR}/ptsr.${SECTOR}.${G_DAY}.${GRID}.bin" >> ${tempdir}/ptsmrg.${PBS_JOBID}.txt
			echo "group num| $groupnums[$n]" >> ${tempdir}/ptsmrg.${PBS_JOBID}.txt

			@ n++
		end

		## Run point source merge for converted inline data for this day
		$execroot/ptsmrg < ${tempdir}/ptsmrg.${PBS_JOBID}.txt

		rm -rf ${tempdir}/qaemis.elev.${PBS_JOBID}.in
cat << ieof > ${tempdir}/qaemis.elev.${PBS_JOBID}.in
$OUTPATH/$OUTFILE
$QADIR/mrgpt.$G_DAY.$GRID.$CASE.camx.tot.txt
$QADIR/mrgpt.$G_DAY.$GRID.$CASE.camx.hrs.txt
$QADIR/mrgpt.$G_DAY.$GRID.$CASE.camx.pave.bin
ieof

		## Run the elevated emissions QA program
		$execroot/qaelev < ${tempdir}/qaemis.elev.${PBS_JOBID}.in
		rm -f ${tempdir}/qaemis.elev.${PBS_JOBID}.in
		rm -f ${tempdir}/ptsr.*.${PBS_JOBID}.bin 

	endif  ## end point source merge 

	@ today = $today + 1

	if ($today == 2010366) then
		set today = 2011001
	endif

end #loop back to next day

exit

