#!/bin/csh -f

# Version @(#)$Id$
# Path    $Source$
# Date    $Date$

# This script sets up needed environment variables for running SMOKE point
# sources using daily and/or hourly emissions for 1 or more months.  The
# "onetime" steps are intended to be run in another script.  This script runs
# only Smkinven (for daily/hourly), Temporal, Laypoint, Smkmerge, optionally
# Smk2emis, and Smkreport for date-specific reports.
#
# This script is intended to be used with the EMF
# source emissions in SMOKE for the EPA 2002 modeling platform, and
# calls the scripts that runs the SMOKE programs.
# 
# Script created by : M. Houyoux, Environmental Protection Agency
# October, 2007
#
#*********************************************************************
  
# set source category
setenv SMK_SOURCE P           # source category to process
setenv MRG_SOURCE $SMK_SOURCE # source category to merge

##############################################################################

switch ( $#argv )
   case 0:
   case 1:
   case 2:
   case 3:
      echo "SCRIPT ERROR: Script requires arguments for a grid name"
      echo "              and the -m or -q option with 3 settings."
      echo " "
      echo "  This script expects to be called using one of the following argument lists:"
      echo "     <grid abbrv> <run type> -m <monthlist> <spinup> <label>"
      echo "     <grid abbrv> <run type> -q <quarters> <spinup> <label>"
      echo " "
      echo "  You can either use one approach or the other (differing by the -m or -q options)."
      echo " "
      echo "  In the above list, the arguments are defined as follows:"
      echo "     <grid abbrv>       : Grid abbreviation (e.g., 36US1)"
      echo "     <run type>         : RUNEXH or STARTEXH"
      echo "     <monthlist>        : list of months to run when using the -m option"
      echo "     <quarters>         : list of quarters to run when using the -q option"
      echo "     <spinup>           : set to number of days between 1 and 20 to run a spinup"
      echo "                          period (value sets number of days), and N otherwise"
      echo "     <label>            : label to put on TIMELOG file and helper-scripts list"
      echo " "
      echo "  Examples:"
      echo "     <script name> 36US1 RUNEXH -m '1 2 3' 0 jan-sep"
      echo "              This example runs the script for Jan, Feb, & Mar"
      echo "              for the 36US1 grid, with no spinup days and"
      echo "              gives a label to the TIMELOG file of jan-sep."
      echo " "
      echo "     <script name> 12EUS1 RUNEXH -q '2 3' 10 apr-sep:"
      echo "               This example runs the script for the 2nd & 3rd quarters,"
      echo "               for the 12EUS1 grid, including 10 spin-up days, and gives"
      echo "               a label to the TIMELOG file of apr-sep."
      exit( 1 )
endsw

# Get the first two options for the grid abbreviation and I/O API grid
setenv GRID "$argv[1]"
setenv RUN_TYPE "$argv[2]"

## source the ASSIGN file
source $ASSIGNS_FILE

## List of all the helper scripts that are run in this script
set emf_cleanup  = $SCRIPTS/run/emf_cleanup.csh
set set_months   = $SCRIPTS/run/set_months_v3.csh
set timetracker  = $SCRIPTS/run/timetracker_v2.csh
set combine_data = $SCRIPTS/run/combine_data_v5.csh
set set_days     = $SCRIPTS/run/set_days_v4.csh
set log_analyzer = $SCRIPTS/log_analyzer/log_analyzer.py
set msg_list     = $SCRIPTS/log_analyzer/known_messages.txt
set duplic_chk   = $SCRIPTS/run/duplicate_check.csh
set python_annl  = $SCRIPTS/annual_report/annual_report.py
set path_parser  = $SCRIPTS/run/path_parser.py


## Invoke script to interpret calling arguments
set exitstat = 0
switch ( $#argv )
   case 4:
      source $set_months $argv[3] "$argv[4]"
      if ( $status != 0 ) set exitstat = 1
   breaksw
   case 5:
      source $set_months $argv[3] "$argv[4]" $argv[5]
      if ( $status != 0 ) set exitstat = 1
   breaksw
   case 6:
      source $set_months $argv[3] "$argv[4]" $argv[5]
      if ( $status != 0 ) set exitstat = 1
      setenv TLABEL $argv[6]
   breaksw
endsw

# Set spinup duration - the set_months will have QA'f the $argv[5] value
if ( $#argv > 4 ) setenv SPINUP_DURATION $argv[5]

# Save spinup array from set_months
set spinup_array = ( $SPINUP_LIST )

## Set naming label
set namelabel = ${SECTOR}_${CASE}_${GRID}
if ( $?TLABEL ) set namelabel = ${namelabel}_$TLABEL

## Record the helper scripts being used
set suffix = _$namelabel.txt
echo "# Helper scripts used for $SECTOR" > $LOGS/helper_scripts_list$suffix
echo $emf_cleanup >> $LOGS/helper_scripts_list$suffix
echo $set_months >> $LOGS/helper_scripts_list$suffix
echo $timetracker >> $LOGS/helper_scripts_list$suffix
echo $combine_data >> $LOGS/helper_scripts_list$suffix
echo $set_days >> $LOGS/helper_scripts_list$suffix
echo $log_analyzer >> $LOGS/helper_scripts_list$suffix
echo $msg_list >> $LOGS/helper_scripts_list$suffix
echo $duplic_chk >> $LOGS/helper_scripts_list$suffix
echo $python_annl >> $LOGS/helper_scripts_list$suffix
echo $path_parser >> $LOGS/helper_scripts_list$suffix

## Set Time Log filename and initialize file
setenv TIMELOG $LOGS/timelog_$namelabel.txt

## Create output directory for adjustment files if the directory does not exist
if ( ! -e $IMD_ROOT/$CASE/${SECTOR}_adj ) then
	mkdir -p $IMD_ROOT/$CASE/${SECTOR}_adj 
	chmod ug+rwx $IMD_ROOT/$CASE/${SECTOR}_adj 
endif

## Set up scripting environment variables prior to calling the Assigns file
setenv SUBSECT $SECTOR                   # set variable for input/output names
setenv SRCABBR $SUBSECT                  # set abbreviation for naming log files
setenv EISECTOR $SECTOR

set monname = ( jan feb mar apr may jun jul aug sep oct nov dec )
set moncode = ( 01 02 03 04 05 06 07 08 09 10 11 12)

# Loop through months as determined from calling arguments
set mc = 0
set diff = 0 
set g_stdate_all = $G_STDATE
set anymerge  = N 
set anytmprep = N

foreach mon ( $MONTHS_LIST )   # MONTHS_LIST set by set_months.csh

   @ mc = $mc + 1   # month array counter

   setenv MONTH   ${monname[$mon]}         # set variable for month name
   setenv SUBSECT ${SECTOR}_$MONTH
   setenv SRCABBR $SUBSECT
   setenv EMF_PERIOD "${MONTH}_${YEAR}"

   source $ASSIGNS_FILE                  # Invoke Assigns file to set for current month

   # Call EMF Client for current period
   setenv MONTH_ARRAY  $mon              # MONTH_ARRAY can have as many months listed as needed
   setenv SPINUP_ARRAY $spinup_array[$mc]

   ## Determine the number of days to run
   setenv T_TYPE all                 # Set temporal type to type for temporal
   setenv SMK_RUN_DATES $SMK_RUN_DATES_2

   source $set_days   # Call script to set dates for run

   ## Determine the number of days to run
   set ndays = `cat $SMK_RUN_DATES | wc -l`
   echo "Number of dates to run for $MONTH" : $ndays

   ## Loop through days of Laypoint, Smkmerge, and optionally Smk2emis
   set n = 0
   set diff = 0
   set g_stdate_sav = $g_stdate_all

   while ( $n < $ndays )   # Expecting M_TYPE == all (for all days of year)

      @ n = $n + 1

      ## Setup for iterating the date in the Assigns file.
      set line = `head -$n $SMK_RUN_DATES | tail -1`
      set mon = `echo $line[2] | cut -c 5-6`
      @ diff = $line[1] - $g_stdate_sav

      setenv G_STDATE_ADVANCE $diff

      source $ASSIGNS_FILE                 # Invoke Assigns file to set new dates

      ## Set EMF_PERIOD for this day
      setenv EMF_PERIOD $ESDATE

      /usr/bin/python /garnet/oaqps/smoke/tempadj/onroad_tmp_adj_pm.py
      # Check status of run to see if it worked. Give error if failed

   end  # End loop over days

   unsetenv G_STDATE_ADVANCE

end  # End loop over parts

### Run the onroad annual summary for temperature unadjusted onroad emissions.
setenv RUN_TYPE "UNADJ"

# Call EMF Client for current period
$EMF_CLIENT -k $EMF_JOBKEY -m "Running annual summary for unadjusted emissions"    ## log w/ EMF server

/usr/bin/python /garnet/oaqps/smoke/tempadj/onroad_ann_sum.py
if ( $status != 0 ) then
	echo "ERROR: Running annual summary for unadjusted emissions"
	$EMF_CLIENT -k $EMF_JOBKEY -m "ERROR: Running annual summary for unadjusted emissions" -t "e" -p $EMF_PERIOD
	exit ( 1 )
endif

### Run the onroad annual summary for temperature adjusted onroad emissions.
setenv RUN_TYPE "ADJ"

# Call EMF Client for current period
$EMF_CLIENT -k $EMF_JOBKEY -m "Running annual summary for adjusted emissions"    ## log w/ EMF server

/usr/bin/python /garnet/oaqps/smoke/tempadj/onroad_ann_sum.py
if ( $status != 0 ) then
	echo "ERROR: Running annual summary for adjusted emissions"
	$EMF_CLIENT -k $EMF_JOBKEY -m "ERROR: Running annual summary for adjusted emissions" -t "e" -p $EMF_PERIOD
	exit ( 1 )
endif

## Check if RUN_SOURCESENS exists, if not set to N
if ( $?RUN_SOURCESENS == 0 ) then
    setenv RUN_SOURCESENS N
endif


## If running source sensitivity
## If ran successfully, add this sector to source sector override file
## used by sectormerge
if ( $exitstat == 0  && $RUN_SOURCESENS == Y ) then
   echo "Adding $SECTOR to source sector override file"
   # Ensure mrrgirddirector for source sector override file is created
   if ( ! -e $IMD_ROOT/$CASE/mrggrid ) then
      mkdir -p $IMD_ROOT/$CASE/mrggrid
      chmod ug+rwx $IMD_ROOT/$CASE/mrggrid
   endif
   
   ## append this sector /w "adj" appended to the source sector override file
   echo ${SECTOR}_adj >> $IMD_ROOT/$CASE/mrggrid/source_sector_override_${CASE}_${GRID}.txt
endif


