#!/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"
echo "         JUN 2002 - Generalized hysplit                  "
echo "         DEC 2005 - Add NAM Alaska"
echo "         APR 2006 - Add AQM, later comment it out to hold 'slot'"
echo "         DEC 2006 - Add zoom, map centering"
echo "         MAY 2007 - met init time labels; per updated volcplot"
echo "         APR 2008 - Add back-tracking (source attribution) capability"
echo "                       replace gfsa with gdas"

# this script reads output from setup script
#             copies already-made ARL-format meteorology files
#             calls script to run HYSPLIT

#####################################################################
set -x

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

###########################
# typenum=1 RSMC
#         2 volcanic ash
#         3 hls/WFO
#         4 back-tracking
###########################
# meteonum=1 HRW
#          2 NAM
#          3 NAM-Alaska
#          4 GFS
#          5 GDAS
###########################

cd $DATA

# save cyc and PDY as determined in job script (these were exported)
#   "cyc" and "PDY" may be changed here to that of currently available meteo
  PDY_org=${PDY}
  cyc_org=${cyc}

#############################################################
# Set last forecast hour of meteorology files
#                              (this also in setup_hypslit)
#############################################################
lfhrh=18	# hi-res window
lfhre=48	# nam hourly (e=eta) 
lfhrg=384	# gfs (changed from 84 to 384 5 Mar 2008)

#############################################################
# Set Model Simulation Variables - Read In SDM Input
#############################################################
cp ${GESDIR}/hysplit.ini hysplit.ini

if [ -s hysplit.ini ]
then
  k=0
  cat hysplit.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 olvl1=$tmp;;
      7)  export olvl2=$tmp;;
      8)  export nhrs=$tmp;;
      9)  export mtype=$tmp;;
      10) export dir1=$tmp;;
      11) export meteo1=$tmp;;
      12) export dir2=$tmp;;
      13) export meteo2=$tmp;;
      14) export dir3=$tmp;;
      15) export meteo3=$tmp;;
      16) export ident=$tmp;;
      17) export qrat=$tmp;;
      18) export qhrs=$tmp;;
      19) export dsyr=$tmp;;
      20) export dsmo=$tmp;;
      21) export dsda=$tmp;;
      22) export dshr=$tmp;;
      23) export dsmn=$tmp;;
      24) export cnlat=$tmp;;
      25) export cnlon=$tmp;;
      26) export dlat=$tmp;;
      27) export dlon=$tmp;;
      28) export splat=$tmp;;
      29) export splon=$tmp;;
      30) export height=$tmp;;
      31) export csyr=$tmp;;
      32) export csmo=$tmp;;
      33) export csda=$tmp;;
      34) export cshr=$tmp;;
      35) export dhr=$tmp;;
      36) export delhr=$tmp;;
      37) export cnlat2=$tmp;;
      38) export cnlon2=$tmp;;
      39) export dlat2=$tmp;;
      40) export dlon2=$tmp;;
      41) export splat2=$tmp;;
      42) export splon2=$tmp;;
      43) export height2=$tmp;;
      44) export dhr2=$tmp;;
      45) export dryvl=$tmp;;
      46) export wetin=$tmp;;
      47) export wetlo=$tmp;;
      48) export rhalf=$tmp;;
      49) export icmt=$tmp;;
      50) export initd=$tmp;;
      51) export khmax=$tmp;;
      52) export numpar=$tmp;;
      53) export isot=$tmp;;
      54) export ndump=$tmp;;
      55) export kmsl=$tmp;;
      56) export seq=$tmp;;
      57) export qunits=$tmp;;	 	
      58) export org=$tmp;;
      59) export zoom1=$tmp;;
      60) export zoom2=$tmp;;
      61) export relcen=$tmp;;
    esac
 done
else
   msg='hysplit.ini file not found -- job terminated'
   postmsg "$jlogfile" "$msg"			
   export err=1; err_exit		
fi

###########add by XXW#################
model=$meteo1
run_id=$site
latitude=$olat
longitude=$olon
let longitude=longitude*-1

if test "$model" = "HIRESW"
then

   NEST=`/nwprod/exec/hiresw_grid_select <<EOF
&LATLON_INPUT
 XLATITUDE=$latitude   ,
XLONGITUDE=$longitude
/
EOF`
else
   NEST=`echo $model | tr [A-Z] [a-z]`
fi

echo "${NEST}  $PDY $cyc $run_id $model"
#########################add by XXW#######################3

#############################################################
# Change nomenclature HIRESW to HRW for consistency with
# using 3 characters (HRW,NAM,GFS)
#############################################################
if [ "$meteo1" = "HIRESW" ]
then
   meteo1=HRW
fi
if [ "$meteo2" = "HIRESW" ]
then
   meteo2=HRW
fi
if [ "$meteo3" = "HIRESW" ]
then
   meteo3=HRW
fi

#############################################################
# Set run type per setup_hysplit
#############################################################
# read words of $title to identify volcanic ash run
  echo $title | read word1 word2 word3 word4

  if [ "$title" = "Test of the RSMC Response System" -o \
       "$title" = "Requested Services" -o \
       "$title" = "IAEA Notified Emergency" ]; then
     export typenum=1					# RSMC ###
  elif [ "$word1" = "volcanic" ]
  then
     export typenum=2					# Volcano ###
     if [ "$word4" = "test" ]
     then
        export alert=0 
        export atyp=-1			
     elif [ "$word4" = "alert" ]
     then
        export alert=0
        export atyp=0
     elif [ "$word4" = "alert watch" ]
     then
        export alert=0
        export atyp=3
     elif [ "$word4" = "alert update" ]
     then
        export alert=0 
        export atyp=1
     fi
  elif [ "$title" = "Test run of the on-demand HYSPLIT Model" -o \
         "$title" = "Real event run of the HYSPLIT Model" ]
     then
     export typenum=3					# Homeland Security ###
  elif [ "$title" = "Test of the Back-tracking System" -o \
         "$title" = "Requested Services" ]
     then
     export typenum=4					# back-tracking 
  else
       msg='ERROR - title does not match setup_hysplit - job terminated'
       postmsg "$jlogfile" "$msg"
       export err=1; err_exit			
  fi

##############################################################
# define TYP for filename
##############################################################
case $typenum in
1) export TYP=rsmc;;
2) export TYP=volc;;
3) export TYP=hls;;
4) export TYP=back;;
esac

#############################################################
#   convert volcanic ash column top from feet to meters
#############################################################
#      hysplit input is in meters, but entering feet is consistent with VAFTAD
#      entering a typical number as thousands of feet (i.e. 25000, 35000),
#        assures an even FL-value (i.e. FL250, FL350) for output charts
#      entering an even number of meters (12000m) results in an oddball value 
#        in FL (FL394)
#==============================================================================
if [ $typenum -eq 2 ]; then
  olvl2=`echo "$olvl2*3048/10000" |bc` # if multiply by .3048, 4 decimals in result
fi

#############################################################
# Define IPDY and Icyc as the met model cycle time less than
# or equal to the Incident time.
#############################################################

export IPDY=$dsyr$dsmo$dsda		

Icyc=$dshr
let Icyc=$Icyc/6*6			
typeset -Z2 Icyc
export Icyc
#############################################################
# Set meteorology file(s)
#############################################################

nfile=0			              # number of meteo files input to HYSPLIT
ifile=0
itype=1
DAT1=
DAT2=
DAT3=
meteo[1]=$meteo1
meteo[2]=$meteo2
meteo[3]=$meteo3
export met1=undefined
export met2=undefined
export met3=undefined
export met4=undefined
export met5=undefined
export met6=undefined
export met7=undefined
export met8=undefined
export met9=undefined

rm -f GDASBACK		# moved from below

while [ $itype -le $mtype ]; do

  # per setup_hysplit
  DAT=`echo ${meteo[$itype]} | cut -c1-4`
 #if [ "`echo $DAT | cut -c4-4`" = "F" ]	# ?????
 #then
 #   DAT=`echo $DAT | cut -c1-3`
 #fi
  if [ "$DAT" = "HRW" ]
  then
     meteonum=1
  elif [ "$DAT" = "NAM" ]
  then
     meteonum=2
  elif [ "$DAT" = "NAMa" ]
  then
     meteonum=3
  elif [ "$DAT" = "GFS" ]
  then
     meteonum=4
  elif [ "$DAT" = "GDAS" ]
  then
     DAT=GDAS
     meteonum=5
  else
       msg='meteo does not match setup_hysplit - job terminated'
       postmsg "$jlogfile" "$msg"
       export err=1; err_exit			
  fi

# force this for labeling; as long as copy Alaska file, should be OK
  if [ "${DAT}" = "NAMa" ]; then
     DAT="NAM"
  fi

  # save for later use 
  if [ $itype -eq 1 ]
  then
     DAT1=$DAT
  elif [ $itype -eq 2 ]
  then
     DAT2=$DAT
  elif [ $itype -eq 3 ]
  then
     DAT3=$DAT
  fi
     
#---------------------------------------------------------------------------
# There are 3 sections here with the same purpose - to determine which
# cycle is the current cycle.  The complicating factor is that 2 meteorology
# files, each from a different cycle may be used by hysplit, for example:
#  NAM - GFS
#  GFS (through F180) - GFS (F180 - F384)
#  GDAS - GFS
#---------------------------------------------------------------------------
  case $meteonum in
  1|2|3|4)

  #############################################################
  # Compute Base Starting Time for Meteorology Forecast
  #   ($cyc defined in JHYSPT) for HRW, NAM, NAMak, GFS, but not GDAS
  #############################################################
   timeset=0
   daysback=0
   while test $timeset -ne 1 -a $daysback -le 6; do
     case $cyc in
     00) case $meteonum in
         # 1) FILE=/com/hls/${envir}/hiresw.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          1) FILE=/com/hls/prod/hysplit.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          2) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namf;;
          3) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namakf;;
          4) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.gfsf;;
         esac
         if test -f ${FILE}
         then
           timeset=1
         else
           PDY=`$utilscript/finddate.sh $PDY d-01`
           cyc=18
           let daysback=$daysback+1
         fi
     ;;
     06) case $meteonum in
         # 1) FILE=/com/hls/${envir}/hiresw.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          1) FILE=/com/hls/prod/hysplit.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          2) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namf;;
          3) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namakf;;
          4) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.gfsf;;
         esac
         if test -f ${FILE}
         then
           timeset=1
         else
           cyc=00
         fi
     ;;
     12) case $meteonum in
         # 1) FILE=/com/hls/${envir}/hiresw.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          1) FILE=/com/hls/prod/hysplit.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          2) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namf;;
          3) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namakf;;
          4) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.gfsf;;
         esac
         if test -f ${FILE}
         then
           timeset=1
         else
           cyc=06
         fi
     ;;
     18) case $meteonum in
         # 1) FILE=/com/hls/${envir}/hiresw.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          1) FILE=/com/hls/prod/hysplit.$PDY/hysplit.t${cyc}z.hireswf.${NEST};;
          2) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namf;;
          3) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namakf;;
          4) FILE=/com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.gfsf;;
         esac
         if test -f ${FILE}
         then
           timeset=1
         else
           cyc=12
         fi
     ;;
     esac
   done

   if test $daysback -gt 6
   then
     msg='${meteo[$itype]} input files not found -- FATAL ERROR'
     postmsg "$jlogfile" "$msg"
     export err=1;err_exit
   fi
   export PDY cyc

 # document current date cycle for this meteorology file
   echo "`head -c8 ${FILE}`" > ${DAT}.ftpdone
   if [ "${COMOUT}" = "YES" ]; then
      cp ${DAT}.ftpdone ${COMOUT}/hysplit.${cycle}.${site}.${TYP}${seq}.${DAT}.ftpdone
   fi

   ;;
   esac

  #############################################################
  # Compute Base Starting Time for Meteorology Forecast for GFSLR
  # GFSLR cycle may differ from GFS cycle if GFSLR is not available yet
  #############################################################
  case $meteonum in
  4)

  # start with PDY/cyc from GFS 
   PDYx=${PDY}
   cycx=${cyc}

   timeset=0
   daysback=0
   while test $timeset -ne 1 -a $daysback -le 6; do
     case $cycx in
     00) FILE2=/com/hysplit/prod/hysplit.$PDYx/hysplit.t${cycx}z.gfslrf
         if test -f ${FILE2}
         then
           timeset=1
         else
           PDYx=`$utilscript/finddate.sh $PDYx d-01`
           cycx=18
           let daysback=$daysback+1
         fi
     ;;
     06) FILE2=/com/hysplit/prod/hysplit.$PDYx/hysplit.t${cycx}z.gfslrf
         if test -f ${FILE2}
         then
           timeset=1
         else
           cycx=00
         fi
     ;;
     12) FILE2=/com/hysplit/prod/hysplit.$PDYx/hysplit.t${cycx}z.gfslrf
         if test -f ${FILE2}
         then
           timeset=1
         else
           cycx=06
         fi
     ;;
     18) FILE2=/com/hysplit/prod/hysplit.$PDYx/hysplit.t${cycx}z.gfslrf
         if test -f ${FILE2}
         then
           timeset=1
         else
           cycx=12
         fi
     ;;
     esac
   done

 # make ftpdone file for labeling if GFSLR is diff cycle than GFS
   if [ ${PDY} -ne ${PDYx} -o ${cyc} -ne ${cycx} ]; then
     #yrx=`echo ${PDYx} | cut -c3-4`
     #mox=`echo ${PDYx} | cut -c5-6`
     #dax=`echo ${PDYx} | cut -c7-8`
     #echo "${yrx}${mox}${dax}${cycx}" > GFSLR.ftpdone
    # document current date cycle for this meteorology file

    # read Y-M-D-H from data file and subtract 180 hours to get GFSLR cycle
      yrx=`head -c2 ${FILE2}`
      if [ ${yrx} -lt 10 ]; then
       yrx=`head -c2 ${FILE2} | cut -c2-2`
      fi
      if [ ${yrx} -lt 2000 ]; then
         let yrx=2000+${yrx}
      fi

      mox=`head -c4 ${FILE2} | cut -c3-4`
      if [ ${mox} -lt 10 ]; then
         mox=`head -c4 ${FILE2} | cut -c4-4`
      fi
      if [ ${mox} -lt 10 ]; then
         mox="0"${mox}
      fi

      dax=`head -c6 ${FILE2} | cut -c5-6`
      if [ ${dax} -lt 10 ]; then
         dax=`head -c6 ${FILE2} | cut -c6-6`
      fi
      if [ ${dax} -lt 10 ]; then
         dax="0"${dax}
      fi

      hrx=`head -c8 ${FILE2} | cut -c7-8`
      if [ ${hrx} -lt 10 ]; then
         hrx=`head -c8 ${FILE2} | cut -c8-8`
      fi
      if [ ${hrx} -lt 10 ]; then
         hrx="0"${hrx}
      fi

      gfslr_cyc=`/nwprod/util/exec/ndate -180 ${yrx}${mox}${dax}${hrx}`
    # strip off leading two digits from year 
      gfslr_cyc=`echo ${gfslr_cyc} | cut -c3-10`
      echo ${gfslr_cyc} > GFSLR.ftpdone

      if [ "${COMOUT}" = "YES" ]; then
         cp GFSLR.ftpdone ${COMOUT}/hysplit.${cycle}.${site}.${TYP}${seq}.GFSLR.ftpdone
      fi
   fi

   if test $daysback -gt 6
   then
     msg='${meteo[$itype]} long range not found - will see if it is needed'
     postmsg "$jlogfile" "$msg"
    #export err=1;err_exit
   fi

  ;; 
  esac

  #dat=`echo ${meteo[$itype]} | tr '[a-z]' '[A-Z]'`   

 ############################################################################
 # count number of metfiles (nfile), this is written to CONTROL file
 # assign met1, met2, etc (met filenames), these are written to CONTROL file
 # met9=GDASBACK for back-tracking, 
 #           and for forward run when rlse starts before start of fcst file
 ############################################################################
 # forecast file(s)
   let nfile=$nfile+1
   export nfile
   case $DAT in
     HRW) export met1=${DAT}F;;
     NAM) export met2=${DAT}F;;
     GFS) export met3=${DAT}F
            let nfile=$nfile+1
            export met8=${DAT}LRF;;
     GDAS) export met9=GDASBACK;;
   esac

 # analysis file for forward runs (exclude back-tracking) 
#    with release starting before the start of the fcst file
   if test $IPDY$Icyc -lt $PDY$cyc -a ${typenum} -ne 4
   then
     let nfile=nfile+1
     export nfile
     case $DAT in
       NAM) export met4=${DAT}A;;
       GFS) 
           #export met5=${DAT}A		# GFSA replaced by GDASBACK May 2008
            export met9=GDASBACK
            ;;
     esac
   fi

  if [ "${met9}" = "GDASBACK" ]
  then

  #############################################################
  # Compute Base Starting Time for GDAS
  #   ($cyc defined in JHYSPT)
  # GDAS date/cyc may be cyc before the GFS date/cyc
  # NOTE cannot have missing time periods in GDASBACK file
  #############################################################
  # use diff variable names to differentiate GFS PDY/cyc
   PDYy=${PDY}
   cycy=${cyc}

   timeset=0
   daysback=0
   while test $timeset -ne 1 -a $daysback -le 6; do
     case $cycy in
     00) FILE=/com/hysplit/prod/hysplit.$PDYy/hysplit.t${cycy}z.gdas1f
         if test -f ${FILE}
         then
           timeset=1
         else
           PDYy=`$utilscript/finddate.sh $PDYy d-01`
           cycy=18
           let daysback=$daysback+1
         fi
     ;;
     06) FILE=/com/hysplit/prod/hysplit.$PDYy/hysplit.t${cycy}z.gdas1f
         if test -f ${FILE}
         then
           timeset=1
         else
           cycy=00
         fi
     ;;
     12) FILE=/com/hysplit/prod/hysplit.$PDYy/hysplit.t${cycy}z.gdas1f
         if test -f ${FILE}
         then
           timeset=1
         else
           cycy=06
         fi
     ;;
     18) FILE=/com/hysplit/prod/hysplit.$PDYy/hysplit.t${cycy}z.gdas1f
         if test -f ${FILE}
         then
           timeset=1
         else
           cycy=12
         fi
     ;;
     esac
   done

   if test $daysback -gt 6
   then
     msg='${meteo[$itype]} input files not found -- FATAL ERROR'
     postmsg "$jlogfile" "$msg"
     export err=1;err_exit
   fi

    # document current date cycle for this meteorology file
      echo "`head -c8 ${FILE}`" > GDAS.ftpdone
      if [ "${COMOUT}" = "YES" ]; then
         cp GDAS.ftpdone ${COMOUT}/hysplit.${cycle}.${site}.${TYP}${seq}.GDAS.ftpdone
      fi

   fi

    #############################################################
    # 	Prepare meteorology for HYSPLIT run
    #     or copy already made files to working directory
    #############################################################

  case $meteonum in
  1) #####################################################################
     # hiresw - 4 km  (forecast only)
     #####################################################################
     #cp /com/hls/${envir}/hiresw.$PDY/hysplit.t${cyc}z.hireswf.${NEST} ${DAT}F
     cp /com/hls/prod/hysplit.$PDY/hysplit.t${cyc}z.hireswf.${NEST} ${DAT}F
     ;;
  2) #############################################################
     # Nam - 12 km - CONUS
     #############################################################
     cp /com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namf ${DAT}F
     cp /com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.nama ${DAT}A
     ;; 
  3) #############################################################
     # Nam - 45 km - Alaska
     #############################################################
     cp /com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namakf ${DAT}F
     cp /com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.namaka ${DAT}A
     ;; 
  4|5) 
     case $meteonum in
     4) #############################################################
        # GFS - 1 degree global lat-lon grid (forecast)
        #    (for $meteonum=5 (GDAS) do not need forecast)
        #############################################################
        cp /com/hysplit/prod/hysplit.$PDY/hysplit.t${cyc}z.gfsf ${DAT}F
        cp ${FILE2} ${DAT}LRF
        ;;
     esac

     if [ "${met9}" = "GDASBACK" ]; then
       #############################################################
       # GDAS - 1 degree global lat-lon grid (analysis)
       # ---------------
       # GDAS used for $meteonum=4 (GFS, when release start before start of fcst)
       #               $meteonum=5 (GDAS, back-tracking)
       # GDAS files named with an "f" because they are from the GDAS 
       #   forecast files
       # hysplit.$cycle.gdas1f  = F00, F03
       # hysplit.$cycle.gdas1fx = F06, F09
       #############################################################

         PDY_list="$PDYm7 $PDYm6 $PDYm5 $PDYm4 $PDYm3 $PDYm2 $PDYm1 $PDY"

       # concatenate successive gdas files
         for pdy in ${PDY_list}
         do

           for gcyc in 00 06 12 18;
           do
 
             if [ ${pdy}${gcyc} -le ${PDYy}${cycy} ]
             then

                GDASFILE=/com/hysplit/prod/hysplit.${pdy}/hysplit.t${gcyc}z.gdas1f 
                if [ -s ${GDASFILE} ]; then
                   cat ${GDASFILE} >> GDASBACK
                else
                 # get the F06,F09 from the previous cycle
                   msg="NOTICE ${GDASFILE} not found, will try to fill in from previous cycle - $0"
                   postmsg "$jlogfile" "$msg"
                   tmp=`/nwprod/util/exec/ndate -6 ${pdy}${gcyc}`
                   tmpday=`echo $tmp | cut -c1-8`
                   tmpcyc=`echo $tmp | cut -c9-10`
                   GDASFILE=/com/hysplit/prod/hysplit.${tmpday}/hysplit.t${tmpcyc}z.gdas1fx
                   if [ -s ${GDASFILE} ]; then
                      cat ${GDASFILE} >> GDASBACK
                   else
                    # if GDASBACK not written yet, then continue otherwise can't have missings
                    #    in GDASBACK file
                      if [ -s GDASBACK ]; then
                         msg="FATAL ${GDASFILE} not found. Cannot have missings in GDASBACK. Delete $pdy and all previous days in PDY_list - $0"
                         postmsg "$jlogfile" "$msg"
                         exit 98 
                      fi
                   fi
                fi

             fi

           done
         done

       case $meteonum in
       4)

       ####################################################################
       # if GFS has been updated, but not GDAS, get the latest F06, F09
       #   so there will be no missings between the end of the GDASBACK
       #   and the start of the GFS
       ####################################################################
       # date/cyc of GFS
         yr=`cat GFS.ftpdone | cut -c1-2`
           if [ $yr -lt 10 ]; then 
              yr=`cat GFS.ftpdone | cut -c2-2`
              yr="0"${yr}
           fi
           let yr=2000+$yr
         mo=`cat GFS.ftpdone | cut -c3-4`
           if [ $mo -lt 10 ]; then 
              mo=`cat GFS.ftpdone | cut -c4-4`
              mo="0"${mo}
           fi
         da=`cat GFS.ftpdone | cut -c5-6`
           if [ $da -lt 10 ]; then 
              da=`cat GFS.ftpdone | cut -c6-6`
              da="0"${da}
           fi
         hr=`cat GFS.ftpdone | cut -c7-8`
           if [ $hr -lt 10 ]; then 
              hr=`cat GFS.ftpdone | cut -c8-8`
              hr="0"${hr}
           fi
         GFScyc=$yr$mo$da$hr 

       # date/cyc of GDAS
         yr=`cat GDAS.ftpdone | cut -c1-2`
           if [ $yr -lt 10 ]; then 
              yr=`cat GDAS.ftpdone | cut -c2-2`
              yr="0"${yr}
           fi
           let yr=2000+$yr
         mo=`cat GDAS.ftpdone | cut -c3-4`
           if [ $mo -lt 10 ]; then 
              mo=`cat GDAS.ftpdone | cut -c4-4`
              mo="0"${mo}
           fi
         da=`cat GDAS.ftpdone | cut -c5-6`
           if [ $da -lt 10 ]; then 
              da=`cat GDAS.ftpdone | cut -c6-6`
              da="0"${da}
           fi
         hr=`cat GDAS.ftpdone | cut -c7-8`
           if [ $hr -lt 10 ]; then 
              hr=`cat GDAS.ftpdone | cut -c8-8`
              hr="0"${hr}
           fi
         GDAScyc=$yr$mo$da$hr 

         if [ ${GFScyc}-${GDAScyc} -gt 6 ]; then

             GDASFILE=hysplit.${PDYy}/hysplit.t${cycy}z.gdas1fx
             if [ -s ${GDASFILE} ]; then
                cat ${GDASFILE} >> GDASBACK
             else
                msg="WARNING - ${GDASFILE} not found.  There is a gap in data between end of GDAS and beginning of GFS.  For the dispersion run, either use the GDAS or GFS alone, or if need both, (1) rerun the prep job so this file exists, or (2) wait until next GDAS cycle is done."
                echo $msg
             fi
         fi

         if [ ${GFScyc}-${GDAScyc} -gt 12 ]; then
             msg="WARNING - There is a gap in data between end of GDAS and beginning of GFS.  For the dispersion run, either use the GDAS or GFS alone, or if need both, wait until next GDAS cycle is done, then rerun."
             echo $msg

         fi
 
         ;;
         esac

fi

;;
esac

# forecast initialization time for plot label
  case $typenum in
  4) 
  export DATlabel="GDAS" ;;
  *)
  echo "`head -c8 ${DAT}F`" > ${DAT}.ftpdone
  cp ${DAT}.ftpdone ${COMOUT}/hysplit.${cycle}.${site}.${TYP}${seq}.${DAT}.ftpdone

  yr=`cat ${DAT}.ftpdone | cut -c1-2`
  if [ ${yr} -lt 10 ]; then
     yr=`cat ${DAT}.ftpdone | cut -c2-2`
  fi
  let yr=2000+${yr}

  mo=`cat ${DAT}.ftpdone | cut -c3-4`
  if [ ${mo} -lt 10 ]; then
     mo=`cat ${DAT}.ftpdone | cut -c4-4`
  fi
  case ${mo} in
  1) mo=Jan;;
  2) mo=Feb;;
  3) mo=Mar;;
  4) mo=Apr;;
  5) mo=May;;
  6) mo=Jun;;
  7) mo=Jul;;
  8) mo=Aug;;
  9) mo=Sep;;
  10) mo=Oct;;
  11) mo=Nov;;
  12) mo=Dec;;
  esac

  da=`cat ${DAT}.ftpdone | cut -c5-6`
  if [ ${da} -lt 10 ]; then
     da=`cat ${DAT}.ftpdone | cut -c6-6`
     da="0"${da}
  fi

  hr=`cat ${DAT}.ftpdone | cut -c7-8`
  if [ ${hr} -lt 10 ]; then
     hr=`cat ${DAT}.ftpdone | cut -c8-8`
     hr="0"${hr}
  fi

  if [ -s GDASBACK ]
  then
     DATlabel="${DATlabel} GDAS"
  fi
  if [ "${DATlabel}" = "" ]
  then
     export DATlabel="${DATlabel} ${hr}00 UTC ${da} ${mo} ${yr} ${DAT}"
  else
     export DATlabel="${DATlabel} and ${hr}00 UTC ${da} ${mo} ${yr} ${DAT}"
  fi
  if [ "${DAT}" = "GFS" ]; then
     if [ -s GFSLR.ftpdone ]; then
       #DATx=`cat GFSLR.ftpdone`
        yr=`cat GFSLR.ftpdone | cut -c1-2`
        if [ ${yr} -lt 10 ]; then
           yr=`cat GFSLR.ftpdone | cut -c2-2`
        fi
        let yr=2000+${yr}

        mo=`cat GFSLR.ftpdone | cut -c3-4`
        if [ ${mo} -lt 10 ]; then
           mo=`cat GFSLR.ftpdone | cut -c4-4`
        fi
        case ${mo} in
        1) mo=Jan;;
        2) mo=Feb;;
        3) mo=Mar;;
        4) mo=Apr;;
        5) mo=May;;
        6) mo=Jun;;
        7) mo=Jul;;
        8) mo=Aug;;
        9) mo=Sep;;
       10) mo=Oct;;
       11) mo=Nov;;
       12) mo=Dec;;
       esac

       da=`cat GFSLR.ftpdone | cut -c5-6`
       if [ ${da} -lt 10 ]; then
          da=`cat GFSLR.ftpdone | cut -c6-6`
          da="0"${da}
       fi

       hr=`cat GFSLR.ftpdone | cut -c7-8`
       if [ ${hr} -lt 10 ]; then
          hr=`cat GFSLR.ftpdone | cut -c8-8`
         hr="0"${hr}
       fi
       export DATlabelGFSLR="${hr}00 UTC ${da} ${mo} ${yr} GFSLR"
     fi
  fi
  ;;
  esac

# completed meteorology of type $itype
  let itype=$itype+1
done

# set meteorology labels for MAPTEXT.CFG
# remove duplicates (ie. A and F)
if [ "$DAT1" = "$DAT3" -o "$DAT2" = "$DAT3" ]
then
   DAT3=
fi 
if [ "$DAT1" = "$DAT2" ]
then
   DAT2=
fi 

# use string length as surrogate for null
len3=`expr "$DAT3" : ".*"`
len2=`expr "$DAT2" : ".*"`
len1=`expr "$DAT1" : ".*"`

# add spaces for MAPTEXT.CFG label
if [ $len3 -ne 0 ]
then
   DAT3=" $DAT3"
fi
if [ $len2 -ne 0 ]
then
   DAT2=" $DAT2"
fi
#export DATlabel="${DAT1}${DAT2}${DAT3}"

#######################################################################
# adjust nhrs (run duration) to not go beyond end of forecast(s)
#
# requirement is
#  release start + run duration <= met init time + last forecast hour
#
# met files in order of increasing forecast length
#######################################################################
case $typenum in
1|2|3)
RUNend=`/nwprod/util/exec/ndate +${nhrs} $dsyr$dsmo$dsda$dshr`
METend=0
if [ -f HRWF ]
then
   MET=`/nwprod/util/exec/ndate +${lfhrh} $PDY$cyc`
   if [ $MET -gt $METend ]; then
      METend=$MET
   fi
fi
if [ -f NAMF ]
then
   MET=`/nwprod/util/exec/ndate +${lfhre} $PDY$cyc`
   if [ $MET -gt $METend ]; then
      METend=$MET
   fi
fi
if [ -f GFSF ]
then
   MET=`/nwprod/util/exec/ndate +${lfhrg} $PDY$cyc`
   if [ $MET -gt $METend ]; then
      METend=$MET
   fi
fi
if [ $RUNend -gt $METend ]
then
   dif=`/nwprod/util/exec/nhour $RUNend $METend`
   let nhrs=$nhrs-$dif
   msg='NOTICE run duration reduced per length of forecast meteorology'
   postmsg "$jlogfile" "$msg"
fi
;;
esac

#############################################################
# Run Trajectory and Concentration Models (HYSPLIT)
#############################################################
$USHhysplit/hysplit_trajconc.sh

########################################################
cp hysplit.ini ${COMOUT}/hysplit.ini

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

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

