#!/bin/csh -f

# The purpose of this script is to set the SMOKE script RUN_ settings from 
# default values using an input file to control the settings.  This is a new
# approach that changes the defaults, which are assumed to be set from the
# main run script. Using this script helps to manage SMOKE runs with many 
# sectors and grids, and for running SMOKE from the EMF without needing 
# to set a separate RUN_ parameter for each SMOKE program and sector.

# There are four arguments for this script, all of which are required.
# The script will abort with an error if it is not called properly
# The syntax for calling the script is:
#      source runsettings.csh  <sector> <grid> <partnum> <juldate> <infile>
# where,
#   <sector>  is the modeling sector that needs to match column 1 of <infile>
#   <grid>    is the grid abbreviation that needs to match column 2 of <infile>
#   <partnum> is PART1, PART2, PART3, or PART4, which needs to match column 4 of <infile>
#   <juldate> is the Julian date from the main script for the current day
#   <infile>  the path and name of the file being used to control the RUN_* settings
#             in the main SMOKE scripts.  <infile> must be a column-delimited file
#             without other commas appearing in columns 1 through 7.  The columns
#             of this file are as follows:
#      Column     Description
#      ------     -----------
#        A        Sector abbreviation or "all" (e.g., SECTOR in Assigns file or EMF script)
#        B        Grid abbreviation (e.g., GRID in Assigns file or EMF scripts)
#        C        Lowercase name of SMOKE program (e.g., smkinven, spcmat, smkmerge)
#        D        Part number cooresponding to the RUN_PART* settings in the SMOKE scripts
#        E        Start date or 0 for programs not affected by dates in the scripts
#        F        End date or 0 for programs not affected by dates in the scripts
#        G        Control - set to Y to run program and N to not run program.
#
#      Notes on <infile> format:
#        - For column A, sector-specific entries will override "all" entries.
#        - All rows not matching script arguments <sector>, <grid>, <partnum>, and <juldate>
#          will be ignored for a given call to the script.
#        - If either columns D or E are set to 0, both will be ignored.
#        - Lowercase values in column G are automatically converted to uppercase.
#        - Full-line comments can use a # sign in the first character of the line.
#        - End-of-line comments can use a ! sign before the comment
#        - <infile> should contain no blank lines unless a comment character is provided


# Interpret script arguments and handle errors for missing arguments
# Check if there are 5 arguments and parse out script arguments
switch ( $#argv )
   case 5: 
      set sector  = $argv[1]
      set grid    = $argv[2]
      set partnum = $argv[3]
      set juldate = $argv[4]
      set infile  = $argv[5]
   breaksw

   default 
      echo "SCRIPT ERROR: Incorrect number of arguments for runsettings.csh"
      echo "              The correct sytax for calling that script is:"
      echo " "
      echo "    runsettings.csh <sector> <grid> <partnum> <juldate> <infile>"
      echo " "
      exit ( 1 )
   breaksw

endsw


# Initializations
set col = (0 0 0 0 0 0 0)       # Number of columns in $infile

# Needs to be consistent with programs_uc
set programs_lc = (smkinven spcmat grdmat smkreport elevpoint temporal \
                   laypoint smkmerge mrggrid smk2emis emisfac mbsetup \
                   premobl cemscan cntlmat grwinven mrgelev normbeis3 \
                   tmpbeis3 m3stat domain movesmrg m3xtract layalloc \
		   normbeis4 tmpbeis4)

# Needs to be consistent with programs_lc
set programs_uc = (SMKINVEN SPCMAT GRDMAT SMKREPORT ELEVPOINT TEMPORAL \
                   LAYPOINT SMKMERGE MRGGRID SMK2EMIS EMISFAC MBSETUP \
                   PREMOBL CEMSCAN CNTLMAT GRWINVEN MRGELEV NORMBEIS3 \
                   TMPBEIS3 M3STAT DOMAIN MOVESMRG M3XTRACT LAYALLOC \
		   NORMBEIS4 TMPBEIS4)

# Initialize internal variables
foreach p ( $programs_lc )
    set set_$p = 0
end

# Get number of lines for file
set nline = `cat $infile | wc -l`

# Loop through input file
set j = 0
while ( $j < $nline )
    @ j = $j + 1
    set line = ( `head -$j $infile | tail -1 | cut -d'!' -f1` )

    # Skip comment lines
    set char1 = `echo $line | cut -c1`
    if ( $char1 == "#" ) goto end_of_loop

    # Populate col array with fields from this line
    set c = 0
    while ( $c < 7 )
        @ c = $c + 1
        set col[$c] = `echo $line | cut -d, -f$c`
    end

    # Skip line if sector is not "all" or $sector
    if ( $col[1] != "all" && $col[1] != $sector ) goto end_of_loop

    # Skip line if $grid is not consistent
    if ( $col[2] != $grid ) goto end_of_loop
    
    # Skip line if $partnum is not consistent
    # 12 Oct 2021: C.Allen added support to put "all" or "ALL" in place of PART1, PART2, etc so that you don't have to worry about the PARTs
    if ( $col[4] != $partnum && $col[4] != "all" && $col[4] != "ALL") goto end_of_loop

    # If both dates are non-zero, then check to see if $date is in range
    if ( $col[5] != 0 && $col[6] != 0 ) then

        # Retrieve day, month, and year from the beginning date
        set beg_da = `echo $col[5] | cut -d\/ -f2`
        set beg_mo = `echo $col[5] | cut -d\/ -f1`
        set beg_yr = `echo $col[5] | cut -d\/ -f3`

        # Retrieve day, month, and year from the ending date
        set end_da = `echo $col[6] | cut -d\/ -f2`
        set end_mo = `echo $col[6] | cut -d\/ -f1`
        set end_yr = `echo $col[6] | cut -d\/ -f3`

        # Turn beginning and ending date into julian dates
        set beg_juldate = `$IOAPIDIR/juldate $beg_mo $beg_da $beg_yr | grep $beg_yr | cut -d"," -f2`
        set end_juldate = `$IOAPIDIR/juldate $end_mo $end_da $end_yr | grep $end_yr | cut -d"," -f2`

        # Skip line if $date is not included in line's date range
        if ( $juldate < $beg_juldate || $juldate > $end_juldate ) goto end_of_loop

    endif

    # Change lowercase values to uppercase
    if ( $col[7] == "n" ) set $col[7] = N
    if ( $col[7] == "y" ) set $col[7] = Y

    # Retrieve value of internal setting for affected by current line    
    set setting = set_$col[3]
    set value = ( `eval echo \$$setting | cut -c1` )  # i.e., set $value to the value of $set_smkinven

    # If value has not already been set by a sector-specific setting,
    #    reset the environment variable based on "all" to the value on this line
    if ( $col[1] == 'all' && $value == 0 ) then  
        set $setting = $col[7]

    # Set value based on sector-specific setting
    else
       set $setting = $col[7]   # This will override any "all" settings
      
    endif    

end_of_loop:
end

# Set master variables from calling routine based on internal ones.
set c = 0
foreach p ( $programs_lc )
    @ c = $c + 1
    set setting = set_$p
#    set value = ( `set | grep $setting | grep -v setting | cut -f2 | cut -c1` )
    set value = ( `eval echo \$$setting | cut -c1` )  # cut is needed to remove training carridge return

    # If current file has changed the internal from the default, the reset master
    if ( $value != 0 ) then
        setenv RUN_$programs_uc[$c] $value
    endif
end

exit ( 0 )
