#!/bin/sh
set +x
#####################################################################
echo "----------------------------------------------------------"
echo "exhysplit.sh - Script To Setup Hysplit Model Run."
echo "----------------------------------------------------------"
echo "History:     1997 - Original Script Submitted by Roland Draxler"
echo "         FEB 1998 - First Implementation of this script   "
echo "                    by David Michaud"
echo "         JUN 1999 - Converted to run on the IBM-SP system"
#####################################################################
set -x

msg="HAS BEGUN"
postmsg "$jlogfile" "$msg"

cd $DATA

#############################################################
# Set Model Simulation Variables - Read In SDM Input
#############################################################
cp /nwges/hysplit/rsmc.ini rsmc.ini

if [ -s rsmc.ini ]
then
  k=0
  cat rsmc.ini | while read tmp
  do
    let k=$k+1
    case $k in
      1)  export title=$tmp;;
      2)  export meteo=$tmp;;
      3)  export site=$tmp;;
      4)  export olat=$tmp;;
      5)  export olon=$tmp;;
      6)  export nfile=$tmp;;
      7)  export dir1=$tmp;;
      8)  export met1=$tmp;;
      9)  export dir2=$tmp;;
      10) export met2=$tmp;;
      11) export year=$tmp;;
      12) export month=$tmp;;
      13) export day=$tmp;;
      14) export hour=$tmp;;
      15) export run=$tmp;;
      16) export dur=$tmp;;
      17) export rate=$tmp;;
      18) export rbot=$tmp;;
      19) export rtop=$tmp;;
      20) export poll=$tmp;;
      21) export syr=$tmp;;
      22) export smo=$tmp;;
      23) export sda=$tmp;;
    esac
 done
else
   msg='rsmc.ini file not found -- job terminated'
   postmsg "$jlogfile" "$msg"
   export err=1; err_exit
fi

#############################################################
# Define IPDY and Icyc as the GFS model cycle time less than
# or equal to the Incident time.
#############################################################
export IPDY=$year$month$day

Icyc=$hour
if test $Icyc -lt 6
then
  Icyc=00
else
  if test $Icyc -lt 12
  then
    Icyc=06
  else
    if test $Icyc -lt 18
    then
      Icyc=12
    else
      Icyc=18
    fi
  fi
fi
export Icyc

#############################################################
# Compute Base Starting Time for GFS or RSM Forecast
#############################################################
case $meteo in
  GFS | BOTH)
   gfstimeset=0
   daysback=0
   while test $gfstimeset -ne 1 -a $daysback -le 6; do
     case $cyc in
     00) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.pgrbf
         if test -f ${GFSFILE}72
         then
           gfstimeset=1
         else
           PDY=`$utilscript/finddate.sh $PDY d-01`
           cyc=18
           let daysback=$daysback+1
         fi
     ;;
     06) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.pgrbf
         if test -f ${GFSFILE}72
         then
           gfstimeset=1
         else
           cyc=00
         fi
     ;;
     12) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.pgrbf
         if test -f ${GFSFILE}72
         then
           gfstimeset=1
         else
           cyc=06
         fi
     ;;
     18) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.pgrbf
         if test -f ${GFSFILE}72
         then
           gfstimeset=1
         else
           cyc=12
         fi
     ;;
     esac
   done
   ;;
  RSM)
   rsmtimeset=0
   daysback=0
   while test $rsmtimeset -ne 1 -a $daysback -le 6; do
     case $cyc in
     00) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.sf
         if test -f ${GFSFILE}24
         then
           rsmtimeset=1
         else
           PDY=`$utilscript/finddate.sh $PDY d-01`
           cyc=18
           let daysback=$daysback+1
         fi
     ;;
     06) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.sf
         if test -f ${GFSFILE}24
         then
           rsmtimeset=1
         else
           cyc=00
         fi
     ;;
     12) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.sf
         if test -f ${GFSFILE}24
         then
           rsmtimeset=1
         else
           cyc=06
         fi
     ;;
     18) GFSFILE=/com/gfs/prod/gfs.$PDY/gfs.t${cyc}z.sf
         if test -f ${GFSFILE}24
         then
           rsmtimeset=1
         else
           cyc=12
         fi
     ;;
     esac
   done
 ;;
esac
if test $daysback -gt 9
then
  msg='No GFS input files found -- FATAL ERROR'
  postmsg "$jlogfile" "$msg"
  export err=1;err_exit
fi
export cycle=t${cyc}z
export PDY cyc


if test $meteo = "RSM" -o $meteo = "BOTH"
then
  export met1=RSM
  export nfile=1

  ############################################################
  # Set forecast cycle equal to event time
  ############################################################
  pdychanged=0
  if test $Icyc -lt $cyc -o $IPDY -lt $PDY
  then
    cychold=$cyc
    PDYhold=$PDY
    cyclehold=$cycle
    cyc=$Icyc
    PDY=$IPDY
    cycle=t${cyc}z
    export cyc PDY cycle
    pdychanged=1
  fi

  #############################################################
  # Determine if the RSM Data is already available in ARL format
  #############################################################
  ARLDATA=0
  rsm=/com/$NET/$envir/$RUN.$PDY/rsm.$cycle.$site
  if test -f $rsm
  then
    cp $rsm $DATA/RSM
  else
    ARLDATA=1
  fi

  if test $ARLDATA -eq 0
  then 
    msg='RSM Datasets Already In ARL Format--Skipping to Trajconc'
    postmsg "$jlogfile" "$msg"
  else
  #############################################################
  # Run RSM Forecast
  #############################################################
    export CENLAT=$olat
    export CENLON=$olon
    export FSTART="00"
    export DATE=$IPDY
    export MODELRECVY=/nwges/${NET}recvy
#    export MODELRECVY=/nwges/test/${NET}recvy

    export jobname='relocate'
    numstart=1
    echo "This is start number ${numstart} for Job rsm."
    echo "${DATE}${cyc}${FSTART}${numstart}" > $MODELRECVY/$RUN.control
    export numstart

    #########################################################
    # Check to see if RSM forecast has started or is complete
    # from another run for this site.
    #########################################################

    RSMGO=0
    cd $com
    lastrsm=`ls -1 relocate.$cycle.bf??.${site} | tail -1`
    cd $DATA
    if test -f $lastrsm
    then
      lastfhr=`echo $lastrsm | cut -c17-18`
      if test $lastfhr -ne 24
      then
        FSTART=$lastfhr
        export FSTART
        frcvr=0
        fhr3=`expr $FSTART + 3`
        msg="Partial RSM forecast found.  RSM forecast will resume at F0${fhr3}"
        postmsg "$jlogfile" "$msg"
        while [ $frcvr -le $lastfhr ] 
        do
          if test $frcvr -le 10 
          then 
            frcvr=0$frcvr 
          fi
          cp $com/relocate.$cycle.SGrbF${frcvr}.${site} $DATA/r_sgbf${frcvr}
          cp $com/relocate.$cycle.SGrbF${frcvr}.ctl.${site} $DATA/r_sgbf${frcvr}.ctl
          cp $com/relocate.$cycle.PGrbF${frcvr}.${site} $DATA/r_pgbf${frcvr}
          cp $com/relocate.$cycle.PGrbF${frcvr}.ctl.${site} $DATA/r_pgbf${frcvr}.ctl
          cp $com/relocate.$cycle.SF${frcvr}.${site} $DATA/r_sigf${frcvr}
          cp $com/relocate.$cycle.BF${frcvr}.${site} $DATA/r_sfcf${frcvr}
          frcvr=`expr $frcvr + 3`
        done
        cp ${MODELRECVY}/r_sigfm.$site $DATA/r_sigim
        cp ${MODELRECVY}/r_sigf.$site $DATA/r_sigi
        cp ${MODELRECVY}/r_sfcf.$site $DATA/r_sfci
      else
        RSMGO=1
        msg="Complete RSM forecast found for $site.  RSM2ARL will begin."
        postmsg "$jlogfile" "$msg"
      fi            
    fi

#
# Define files containing initial conditions and base fields
#
    export BASENET=gfs
    export BASERUN=gfs
#    export BASEDIR=/com/$BASENET/${envir}/$BASENET.$PDY
    export BASEDIR=/com/$BASENET/prod/$BASENET.$PDY
    export BASESFCA=$BASEDIR/$BASERUN.$cycle.sfcanl
    export BASESIGA=$BASEDIR/$BASERUN.$cycle.sanl
    export BASESIGF=$BASEDIR/$BASERUN.$cycle.sf'$fcsthr'

########################################################
#          Define files for program input.
########################################################
    export DELX=40000
    export DELY=40000
    export LEFTGRD=73
    export BOTMGRD=73

    export FINT=3
    export PINT=3
    export FEND=24
    export IMX=145
    export JMX=144
    export LVL=28
    export JCAP=126
    export MODL=$IMX.$JMX.$LVL

    export rsmfexec=$EXECrsm/rsm_freloc_$JCAP$LVL
    export rinpexec=$EXECrsm/rsm_ireloc_$JCAP$LVL
    export rmtnexec=$EXECrsm/rsm_treloc
    export rpijexec=$EXECrsm/rsm_polarij
    export rpgbexec=$EXECrsm/rsm_pgrb
    export rsgbexec=$EXECrsm/rsm_sgrb

    export o3clim=$FIXrsm/o3.clim.mrf
    >o3clim.blank
    export o3clim=o3clim.blank
    export co2const=$FIXrsm/co2const.l${LVL}.mrf
    export cldtune=$FIXrsm/cloudtune_2.clim.mrf
    export mtnvar=$FIXrsm/mtnvar6.t${JCAP}.mrf
    export rinpparm=$PARMrsm/rsm_rinpparm.${RUN}
    export rsmfparm=$PARMrsm/rsm_rsmfparm.${RUN}
    export topodata=$FIXrsm/navydata
    export zmoddata=$FIXrsm/zmod2.fmt
    export zmaxdata=$FIXrsm/zmax2.fmt
    export rmtnoro=$DATA/rmtnoro.${RUN}
    export rmtnors=$DATA/rmtnors.${RUN}
    export rmtnvar=$DATA/rmtnvar6.${RUN}
    export rmtnorg=$DATA/rmtnoso.${RUN}
    export rmtnslm=$DATA/rmtnslm.${RUN}
    export rsmlocation=$DATA/rsmlocation.${RUN}

    ##############################################
    # Make RSM Forecast from $FSTART to F24
    ##############################################
    if test $RSMGO -eq 0
    then
       $USHrsm/rsm_relocate.sh
    fi

    #############################################################
    # Convert RSM Grib Into a ARL Formatted File
    #############################################################
    $USHhysplit/hysplit_rsmdata.sh
  fi
        
  #############################################################
  # Run Trajectory and Concentration Models (HYSPLIT)
  #############################################################
  #
  if (test $meteo = "RSM")
  then
    $USHysplit/hysplit_trajconc.sh
  fi

  if test $pdychanged -eq 1
  then
    export cyc=$cychold
    export PDY=$PDYhold
    export cycle=$cyclehold
  fi

fi

if test $meteo = "GFS" -o $meteo = "BOTH"
then
  if test $IPDY$Icyc -ge $PDY$cyc
  then
    export met1=GFSF
    export nfile=1
  else
    export met1=GFSA
    export met2=GFSF
    export nfile=2
  fi

  #############################################################
  # Determine if the GFS Data is already available in ARL format
  #############################################################
  ARLDATA=0
  if test $nfile -eq 1
  then
    gfsf=/com/$NET/${envir}/$RUN.$PDY/GFSF.$cycle.$site
    if test -f $gfsf
    then
      cp $gfsf $DATA/GFSF
    else
      ARLDATA=1
    fi
  else
    gfsa=/com/$NET/${envir}/$RUN.$PDY/GFSA.$cycle.$site
    gfsf=/com/$NET/${envir}/$RUN.$PDY/GFSF.$cycle.$site
    if test -f $gfsa -a -f $gfsf
    then
      cp $gfsa $DATA/GFSA
      cp $gfsf $DATA/GFSF
    else
      ARLDATA=1
    fi
  fi

   ################################################################
   # If we are using a data set already converted to ARL format
   # make sure that the LAT + LON are the same in this run as in
   # the run that created the data set.
   ################################################################
   if test $ARLDATA -eq 0
   then
     gesfil=/nwges/$NET/$site.control
     if test -f $gesfil
     then
       oldlat=`cat $gesfil | awk '{print $5}'`
       oldlon=`cat $gesfil | awk '{print $6}'`
       if test $oldlat -ne $olat -o $oldlon -ne $olon
       then
         ARLDATA=1
         msg="LAT or LON of $site has changed in control file, rerunning GFS2ARL!"
         postmsg "$jlogfile" "$msg"
       fi
     else
       ARLDATA=1
       msg="No control file found for $site, rerunning GFS2ARL!"
       postmsg "$jlogfile" "$msg"
     fi
   fi

  if test $ARLDATA -eq 0
  then 
    msg='GFS Datasets Already In ARL Format--Skipping to Trajconc'
    postmsg "$jlogfile" "$msg"
  else
    #############################################################
    # Convert GFS Grib Into a ARL Formatted File 
    #############################################################
    $USHhysplit/hysplit_gfsdata.sh
  fi
   
  #############################################################
  # Run Trajectory and Concentration Models (HYSPLIT)
  #############################################################
  if (test $meteo = "GFS")
  then
    $USHhysplit/hysplit_trajconc.sh
  fi
fi

if (test $meteo = "BOTH")
then
  if test $nfile -eq 1
  then
    export met1=RSM
    export met2=GFSF
    export nfile=2
    $USHhysplit/hysplit_trajconc.sh
  else
    export met1=RSM
    export met2=GFSA
    export met3=GFSF
    export nfile=3
    $USHhysplit/hysplit_trajconc.sh
  fi
fi

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

msg='ENDED NORMALLY.'
postmsg "$jlogfile" "$msg"

################## END OF SCRIPT #######################

