#! /bin/sh
# set -nv

echo "-----------------------------------------------------------"
echo "               hysplit_prep.sh			  	"
echo "-----------------------------------------------------------"
# revised: 31 May 2006 - generalized per variables in job-script
#                          JHYSPT_*_PREP
#          22 Dec 2006 - missing grib files; nam-egrd3d
#          28 Dec 2007 - run chkmiss only if file missing
#          09 Mar 2011 - nam bgrd 
# ---------------------------------------------------------------
set -x

  fhr_list=$1
  echo ${fhr_list} | read fhr rest
  export lab=$fhr

  mkdir $fhr
  cd $fhr
  ##############################
  # Run setup to initialize working directory and utility scripts
  ##############################
  sh $utilscript/setup.sh

# for acumulation/averaged fields (precip, etc)
  if [ ${fhr} -eq ${lab} ]	
  then
   # for NAMS get +3 from prev cycle (only need precip) so can take diff at +6 h
   #     assumes $fhr is multiple of 6 because of 3-h precip bucket
   #     and at +0 there is no precip so can't start at fhr=3
 #                                       # 7-1-11 NEST created in exhysplit_prep.sh.sms for FW and HI nests
 #                                       #        for nests, we use f06 instead of f00
     if [ "${MDL}" = "NAMS" ]	
     then

     if [ ${NEST} -eq 0 ]	
     then

        if [ ${fhr} -eq 0 ]; then
         # cycle before $PDY$cyc
           tmp=`/nwprod/util/exec/ndate -${CYC_INT} ${PDY}${cyc}`
           xcyc=`echo $tmp | cut -c9-10`
           xday=`echo $tmp | cut -c1-8`
           fhr6=${CYC_INT}
           let fhr3=${fhr6}-3
           if [ $fhr3 -lt 10 ]; then
              fhr3="0"${fhr3}
           fi 
           MDLFILE=${COMMDLIN}/${mdlday}.${xday}/${prefix}.t${xcyc}z.${fname}${fhr3}${sfx}
           NMMPROF=${COMMDLIN}/${mdlday}.${xday}/${prefix}.t${xcyc}z.nmmprofile.${fhr3}.txt
           if [ ! -f ${MDLFILE} ]; then
            # $MDLFILE is missing, get it from previous cycle
              $USHhysplit/hysplit_prep_chkmiss.sh ${MDLFILE} ${xday} ${xcyc} ${fhr3}
              if [ -f MDLfile.${lab} ]; then
                 MDLFILE=`cat MDLfile.${lab}`
                 rm MDLfile.${lab}
              else
                 echo "ERROR - exceed allowable number of missing cycles"
                 exit 201
              fi
           fi
        elif [ ${fhr} -gt 0 ]; then
          let fhr3=${fhr}-3
          if [ $fhr3 -lt 10 ]; then
             fhr3="0"${fhr3}
          fi 
          MDLFILE=${COMMDLIN}/${mdlday}.${PDY}/${prefix}.t${cyc}z.${fname}${fhr3}${sfx}
          NMMPROF=${COMMDLIN}/${mdlday}.${PDY}/${prefix}.t${cyc}z.nmmprofile.{fhr3}.txt
          if [ ! -f ${MDLFILE} ]; then
           # $MDLFILE is missing, get it from previous cycle
             $USHhysplit/hysplit_prep_chkmiss.sh ${MDLFILE} ${PDY} ${cyc} ${fhr3}
             if [ -f MDLfile.${lab} ]; then
                MDLFILE=`cat MDLfile.${lab}`
                rm MDLfile.${lab}
             else
                echo "Terminate - exceed allowable number of missing cycles"
                exit 203
             fi
          fi

        fi

        precip=d	# difference
        ex=2		# 2-d fields only
        INIT=		# not used for nams

      # get nmmprofile.txt file describing vertical levels
        if [ "${mdlcom}" = "nams" ]
        then
           rm -f nmmprofile.txt
           if [ -s ${NMMPROF} ]
           then
              cp ${NMMPROF} nmmprofile.txt
           else
              msg="hysplit_nmmb2arl will use default values"
              $DATA/postmsg "$jlogfile" "$msg"
           fi
        fi

        pgm=hysplit_${convert}
        export pgm;. $DATA/prep_step
        msg="hysplit_${convert} ${MDLFILE} started"
        $DATA/postmsg "$jlogfile" "$msg"

      # add ln -s here so use $MDLFILE without full path /meso/noscrub/...	# ARL 5-16-2011
      #    otherwise complete filename too long for hysplit_${convert}
      #    e.g. /meso/noscrub/wx20er/com/hysplit/prod/nam.20110516/nam.t00z.hawaiinest.bgrd3d03.tm00
        klen=`expr "$MDLFILE" : ".*"`
        if [ ${klen} -gt 77 ]
        then
           ln -s ${MDLFILE}
         # extract filename portion only of complete filename e.g. without path
           MDLFILE=${MDLFILE##*/}
           if [ "${MDLFILE}" = "" ]
           then
              echo "FATAL - MDLFILE not identified"
              exit 70
           fi
        fi

        $EXEChysplit/hysplit_${convert} ${dashi}${MDLFILE}  \
                                        ${dashg}            \
                                        ${dashp}${precip}   \
                                        ${dashv}            \
                                        ${dashs}            \
                                        ${dasha}            \
                                        ${dashx}${ex}       \
                                        ${dashz}${INIT}     \
                                                >> $pgmout 2>errfile	
        export err=$?;$DATA/err_chk
      # for testing
        echo "$EXEChysplit/hysplit_${convert} ${dashi}${MDLFILE} ${dashg} ${dashp}${precip} ${dashv} ${dashs} ${dasha} ${dashx}${ex} ${dashz}${INIT}" >> MESSAGE.fcst.${lab}
       #cp -p RAIN.SUM RAIN.SUM.3
       #cp -p RAIN.3HR RAIN.3HR.3
       #cp -p DATA.NAMS DATA.NAMS.3
        cp -p MESSAGE  MESSAGE.3
        tail -n 15 MESSAGE | head -6 >> MESSAGE.fcst.${lab}
       #tail MESSAGE >> MESSAGE.fcst.${lab}
     fi

     fi

   # need 6-hour fcst from previous cycle valid at forecast init time (fhr=0)

     if [ ${fhr} -eq 0 ]; then

      # cycle before $PDY$cyc
        tmp=`/nwprod/util/exec/ndate -${CYC_INT} ${PDY}${cyc}`
        xcyc=`echo $tmp | cut -c9-10`
        xday=`echo $tmp | cut -c1-8`
        fhr6=${CYC_INT}
        MDLFILE=${COMMDLIN}/${mdlday}.${xday}/${prefix}.t${xcyc}z.${fname}${fhr6}${sfx}
        NMMPROF=${COMMDLIN}/${mdlday}.${xday}/${prefix}.t${xcyc}z.nmmprofile.${fhr6}.txt
        if [ "${mdl}" = "sref" ]; then
           MDLFILE=${COMMDLIN}/${mdlday}.${xday}/${xcyc}/pgrb/${mdl2}.t${xcyc}z.${fname}.${mem}.f${fhr6}
        fi
       #if [ "${MDL}" = "RUC" -a "${fhr}" = "00" ]; then
       # # no test needed here since this is the forecast from the previous cycle
       #fi
        if [ ! -f ${MDLFILE} ]; then
         # $MDLFILE is missing, get it from previous cycle
           $USHhysplit/hysplit_prep_chkmiss.sh ${MDLFILE} ${xday} ${xcyc} ${fhr6}
           if [ -f MDLfile.${lab} ]; then
              MDLFILE=`cat MDLfile.${lab}`
              rm MDLfile.${lab}
           else
              echo "Terminate - exceed allowable number of missing cycles"
              exit 205
           fi
        fi

        if [ "${mdl}" = "gfs" ]; then
           INIT=1
        else
           INIT=
        fi

      # NAMS only; mdl=nam for nam, namak, and nams (do this for nests, too)
        if [ "${MDL}" = "NAMS" ]	
        then
          precip=d
          ex=2
          if [ ${NEST} -eq 1 ]
          then
           # get all fields at f06 valid at f00
             ex=1
          fi
        else
          precip=
          ex=
        fi

      # get nmmprofile.txt file describing vertical levels
        if [ "${mdlcom}" = "nams" ]
        then
           rm -f nmmprofile.txt
           if [ -s ${NMMPROF} ]
           then
              cp ${NMMPROF} nmmprofile.txt
         # else
         #    hysplit_nmmb2arl will use default values
           fi
        fi

        pgm=hysplit_${convert}
        export pgm;. $DATA/prep_step
        msg="hysplit_${convert} ${MDLFILE} started"
        $DATA/postmsg "$jlogfile" "$msg"
      # add ln -s here so use $MDLFILE without full path /meso/noscrub/...	# ARL 5-12-2011
        klen=`expr "$MDLFILE" : ".*"`
        if [ ${klen} -gt 77 ]
        then
           ln -s ${MDLFILE}
         # extract filename portion only of complete filename e.g. without path
           MDLFILE=${MDLFILE##*/}
           if [ "${MDLFILE}" = "" ]
           then
              echo "FATAL - MDLFILE not identified"
              exit 71
           fi
        fi
        $EXEChysplit/hysplit_${convert} ${dashi}${MDLFILE}  \
                                        ${dashg}            \
                                        ${dashp}${precip}   \
                                        ${dashv}            \
                                        ${dashs}            \
                                        ${dasha}            \
                                        ${dashx}${ex}       \
                                        ${dashz}${INIT}     \
                                                  >> $pgmout 2>errfile	
        export err=$?;$DATA/err_chk

      # for testing
        if [ "${MDL}" = "NAMS" ]	
        then
           echo "$EXEChysplit/hysplit_${convert} ${dashi}${MDLFILE} ${dashg} ${dashp}${precip} ${dashv} ${dashs} ${dasha} ${dashx}${ex} ${dashz}${INIT}" >> MESSAGE.fcst.${lab}
          #cp -p RAIN.SUM RAIN.SUM.6
          #cp -p RAIN.3HR RAIN.3HR.6
          #cp -p DATA.NAMS DATA.NAMS.6
           cp -p MESSAGE  MESSAGE.6
           tail -n 15 MESSAGE | head -6 >> MESSAGE.fcst.${lab}
          #tail MESSAGE >> MESSAGE.fcst.${lab}
        fi

     fi

  fi
# ====================== end of 1st fcst hour section ===========================

# now DATA.${MDL} exists with data valid at start time of forecast file

# for nests take out hour f00 since using f06 from above (diagnostic variables missing at f00)
#       and save output from f06
  echo ${fhr_list} | read fhr rest
  if [ ${NEST} -eq 1 -a ${fhr} -eq 0 ]
  then
    fhr_list=${rest}
    mv DATA.${MDL} ../DATA.${MDL}.00
  fi

  for fhr in $fhr_list
  do
    MDLFILE=${COMMDLIN}/${mdlday}.$PDY/${prefix}.t${cyc}z.${fname}${fhr}${sfx}
  # if filename has greater number of chars than input by convert to arl program (pakndx) 
  # then copy file to working directory
  #   e.g. /meso/noscrub/wx20er/com/nam/para/nam.20110131/nam.t12z.firewxnest.bgrd3d03.tm00
    klen=`expr "$MDLFILE" : ".*"`
    if [ ${klen} -gt 77 ]
    then
       cp ${MDLFILE} ./
    fi
    NMMPROF=${COMMDLIN}/${mdlday}.$PDY/${prefix}.t${cyc}z.nmmprofile.${fhr}.txt
    if [ "${mdl}" = "sref" ]; then
       MDLFILE=${COMMDLIN}/${mdlday}.${PDY}/${cyc}/pgrb/${mdl2}.t${cyc}z.${fname}.${mem}.f${fhr}
    fi
# GSM  RAP code uses f00 instead of anl in file names
#    if [ "${MDL}" = "RUC" -a "${fhr}" = "00" ]; then
#     # strip off "f" fname2=pgrb20 fname=pgrb20f
#       fname2=`echo ${fname} | cut -f1 -df`
#       MDLFILE=${COMMDLIN}/${mdlday}.${PDY}/${prefix}.t${cyc}z.${fname2}"anl"${sfx}
#    fi
    if [ ! -f ${MDLFILE} ]; then
     # $MDLFILE is missing, get it from previous cycle
       if [ "${mdl}" = "sref" ]; then
          ls -l ${COMMDLIN}/${mdlday}.${PDY}/${cyc}/pgrb/${mdl2}.t${cyc}z.${fname}.${mem}.f*
       fi
#       if [ "${MDL}" = "RAP" -a "${fhr}" = "00" ]; then
#          ls -l ${COMMDLIN}/${mdlday}.${PDY}/${prefix}.t${cyc}z.${fname2}*${sfx}
#       fi
       $USHhysplit/hysplit_prep_chkmiss.sh ${MDLFILE} ${PDY} ${cyc} ${fhr}
       if [ -f MDLfile.${lab} ]; then
          MDLFILE=`cat MDLfile.${lab}`
          rm MDLfile.${lab}
       else
          echo "Terminate - exceed allowable number of missing cycles"
          exit 207
       fi
    fi

    if [ "${MDL}" = "NAMS" ]	
    then
       if [ $fhr -eq 0 ]; then
          precip=p
       else
          precip=d
       fi
       ex=1
    else
       precip=
       ex=
    fi

    if [ "${mdl}" = "gfs" ]; then
      INIT=0
    else
      INIT=
    fi

  # get nmmprofile.txt file describing vertical levels
    if [ "${mdlcom}" = "nams" ]
    then
       rm -f nmmprofile.txt
       if [ -s ${NMMPROF} ]
       then
          cp ${NMMPROF} nmmprofile.txt
       else
          msg="hysplit_nmmb2arl will use default values"
          $DATA/postmsg "$jlogfile" "$msg"
       fi
    fi

    pgm=hysplit_${convert}
    export pgm;. $DATA/prep_step
    msg="hysplit_${convert} ${MDLFILE} started"
    $DATA/postmsg "$jlogfile" "$msg"
     $EXEChysplit/hysplit_${convert} ${dashi}${MDLFILE}  \
                                    ${dashg}            \
                                    ${dashp}${precip}   \
                                    ${dashv}            \
                                    ${dashs}            \
                                    ${dasha}            \
                                    ${dashx}${ex}       \
                                    ${dashz}${INIT}   \
                                              >> $pgmout 2>errfile

  # for NAMS testing
    if [ "${MDL}" = "NAMS" ]
    then
      echo "$EXEChysplit/hysplit_${convert} ${dashi}${MDLFILE} ${dashg} ${dashp}${precip} ${dashv} ${dashs} ${dasha} ${dashx}${ex} ${dashz}${INIT}" >> MESSAGE.fcst.${lab}
      cp -p MESSAGE MESSAGE.${fhr}
      tail -n 15 MESSAGE | head -6 >> MESSAGE.fcst.${lab}
     #tail MESSAGE >> MESSAGE.fcst.${lab}
    fi

    export err=$?;$DATA/err_chk
  # save DATA.${MDL} with unique name for later concatenation 
  #   and move to common directory
    mv DATA.${MDL} ../DATA.${MDL}.${fhr}

  done
  cd $DATA

  exit
