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

unset verbose

limit stacksize unlimited
## Manually set directory names [**change**]
setenv INSTALL_DIR "/garnet/work/cvy/for_package"
setenv MET_ROOT "/garnet/oaqps/met/MCIP_v4.1.3/WRF_2011g_25aL" # Change to point to your MCIP
setenv WRF_ROOT "/sol/work/ROMO/met/wrfcamx_v4.0/12US2.TZ0/2011_Kvmin0.1_cloud" # Change to point to your WRF

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

set casescripts = $INSTALL_DIR/$CASE/scripts/camx
set camxscripts = $INSTALL_DIR/camx
set SPECIES_MAPPING = $camxscripts/Species_Mapping_Tables/MAPTBL.CMAQ_CB05+AERO6_to_CAMXv6_CB05+CF+RTRACPM_2015feb17

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 = Y  ## 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 = $INSTALL_DIR/$CASE/smoke_out  ## Model ready emissions SMOKE out platform root
set INLN_ROOT = $EMIS_ROOT

# SECTORLIST 
set SECTORLIST = $casescripts/sectorlist
set ptprescfire_path = $EMIS_ROOT/$CASE/$GRID/$SPEC/ptprescfire3D  # Path to CAMx converted ptfire files
set ptwildfire_path = $EMIS_ROOT/$CASE/$GRID/$SPEC/ptwildfire3D  # Path to CAMx converted ptfire files

set YEAR = 2011
set datefile = $camxscripts/dates/mergedates_${YEAR}.txt
set execroot = $camxscripts/bin # Root to cmaq2camx executables

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

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

set today = $start_date

set QADIR = $casescripts/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 = $casescripts/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 $casescripts/$SCRIPTLOG) then
	rm $casescripts/$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 >> $casescripts/$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}/${SPEC}
		set FILEA = emis_mole_all_${G_DAY}_${GRID}_${SPEC}_${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} >> $casescripts/$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-21oct2013 << 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
		set MET = $WRF_ROOT
		set LUPATH = $camxscripts/land

$camxscripts/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}.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

$camxscripts/seasalt/mrgspc.lnx << EOF
Input File         |$EMISPATH/emis2d.$G_DAY.$GRID.$CASE.camx
Input File         |$EMISPATH/seasalt.$today.$GRID.${LAYERS}.camx
Input File         |END
Output File        |$OUTFILE
EOF
		rm -f $EMISPATH/seasalt.$today.$GRID.${LAYERS}.camx 
#		rm -f $EMISPATH/emis2d.$G_DAY.$GRID.$CASE.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 ptnonipm pt_oilgas 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/${SPEC}
			set inln = $INPATH/$SECTOR/inln_mole_${SECTOR}_${repday}_${GRID}_${SPEC}_${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 >> $casescripts/$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-21oct2013 << 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
		set firesectors = (ptprescfire3D ptwildfire3D)
		set firepaths = ($ptprescfire_path $ptwildfire_path)
		# Total number of sectors including all subsectors
		set numsect = `echo $firesectors | wc | awk '{print $2}'`
		set n = 1
		while ($n <= $numsect)
			set firesector = $firesectors[$n]
			set fire_path = $firepaths[$n]
			if (! -d ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/${firesector}) then
				mkdir -p ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/${firesector}
			endif
			rm -f ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/${firesector}/ptsr.${firesector}.${G_DAY}.${GRID}.bin
			ln -s $fire_path/ptsr.${firesector}.${G_DAY}.${GRID}.bin ${EMIS_ROOT}/${CASE}/${GRID}/camx/sector/${firesector}/ptsr.${firesector}.${G_DAY}.${GRID}.bin
			@ n++
		end

		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 ptwildfire3D ptprescfire3D ptnonipm pt_oilgas othpt) 
		set groupnums = (1   2            3             4         5        6    )

		# Total number of sectors including all subsectors
		set numsect = `echo $sectors | wc | awk '{print $2}'`

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

		set n = 1
		while ($n <= $numsect)
			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

