#! /bin/sh

# set -nv

set +x
echo "----------------------------------------------------------------------- "
echo " 		hysplit_prep_arch.sh                                          "
echo "----------------------------------------------------------------------- "
#
# Create an archive file valid at forecast hours +0 and +3 for given DAY/CYCLE
################################################################################
# 1st - write +6 hour fields from previous forecast to DATA.AQM
# 2nd - overwrite with +0 hour fields from current fcst (except ppt, fluxes)
#         cat DATA.AQM >> AQMA; rm DATA.AQM
# 3rd - write +1 hour fields to DATA.AQM
#         cat DATA.AQM >> AQMA, etc for +2, +3, +4, +5

# Revised - 26 May 2006 for missing cycle 
#                       generalized for MDL, etc in job-script
#                          JHYSPT_*_PREP
#           04 Oct 2006 for WRF (nam...egrd3d...)
#           22 Dec 2006 missing grib files
#           28 Dec 2007 - run chkmiss only if file missing
#           09 Mar 2011 - nam bgrd
################################################################################
  set -x

  if [ "${which_nest}" = "firewx" ]
  then
     echo "Not checking for same firewx domain. so cannot make analysis file. "
     echo "Set LEN_ARC in J-job to 0."
     exit 77
  fi

  tday=$1
  tcyc=$2
  loop=$3

# put output file in separate directory
  mkdir -m 775 -p $tday$tcyc
  cd $tday$tcyc
  sh $utilscript/setup.sh

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

  loopmax=`expr ${CYC_INT} / ${FHR_INT} + 1`
  while [ $loop -le $loopmax ]
  do
     if [ $loop -eq 0 ] 
     then
      # (nams only)
      # cycle before $tday
        tmp=`/nwprod/util/exec/ndate -${CYC_INT} ${tday}${tcyc}`
      # hysplit_nams2arl needs RAIN.SUM and RAIN.3HR in order to run the +6
        let fhr=${CYC_INT}-3
      # make sure that there is a leading zero
        stg=$fhr
        indx=0
        while [ "$stg" != '' ];
        do
          stg=${stg#?}
          let indx=$indx+1
        done
        let len=$indx
        if [ $len -eq 1 ];then
           fhr="0"${fhr}
        fi
        xcyc=`echo $tmp | cut -c9-10`
        xday=`echo $tmp | cut -c1-8`
        precip=d
        ex=2
     elif [ $loop -eq 1 ]
     then
        # cycle before $tday
        tmp=`/nwprod/util/exec/ndate -${CYC_INT} ${tday}${tcyc}`
        fhr=${CYC_INT}
        xcyc=`echo $tmp | cut -c9-10`
        xday=`echo $tmp | cut -c1-8`
      # NAMS only; mdl=nam for nam, namak, and nams (do this for nests, too)
      #   (this section also in hysplit_prep.sh)
        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

     else
        xcyc=$tcyc
        xday=$tday
        if [ $loop -eq 2 ]
        then
           fhr="00"
           if [ "${MDL}" = "NAMS" ]	
           then 
              precip=p
              ex=1
           fi
        else
           if [ "${MDL}" = "NAMS" ]
           then 
              precip=d
              ex=1
           fi
         # set fhr=FHR_INT, but make sure that there is a leading zero
           let fhr=$fhr+${FHR_INT}
           stg=${fhr}
           indx=0
           while [ "$stg" != '' ];
           do
             stg=${stg#?}
             let indx=$indx+1
           done
           let len=$indx
           if [ $len -eq 1 ];then
             fhr="0"${fhr}
           fi
        fi
     fi

     skip00=0
     if [ ${NEST} -eq 1 -a ${fhr} -eq 0 ]
     then
     # for nests, use f06 previous cycle instead of f00
       skip00=1
     fi

     if [ ${skip00} -eq 0 ]
     then

     MDLFILE=${COMMDLIN}/${mdlday}.${xday}/${prefix}.t${xcyc}z.${fname}${fhr}${sfx}
     NMMPROF=${COMMDLIN}/${mdlday}.${xday}/${prefix}.t${xcyc}z.nmmprofile.${fhr}.txt	# nmmb only
# GSM no longer needed for RAP
#     if [ "${MDL}" = "RUC" -a "${fhr}" = "00" ]; then
#      # strip off "f" fname2=pgrb20 fname=pgrb20f
#        fname2=`echo ${fname} | cut -f1 -df`
#        MDLFILE=${COMMDLIN}/${mdlday}.${xday}/${prefix}.t${xcyc}z.${fname2}"anl"${sfx}
#     fi

   # $MDLFILE is missing, get it from previous cycle
     if [ ! -f ${MDLFILE} ]; then
          $USHhysplit/hysplit_prep_chkmiss.sh ${MDLFILE} ${xday} ${xcyc} ${fhr}
          if [ -f MDLfile.${lab} ]; then
             MDLFILE=`cat MDLfile.${lab}`
             rm MDLfile.${lab}
          else
             echo "Terminate - exceed allowable number of missing cycles"
             exit 102
          fi
     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"

      # 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

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

     fi
   # end skip f00 for nests

     if [ $loop -gt 1 ]
     then
        if [ -s DATA.${MDL} ]
        then
           cat DATA.${MDL} >> ${MDL}A
           rm DATA.${MDL}
        else
           msg="WARNING - DATA.${MDL} not created - analysis file will not be created."
           $DATA/postmsg "$jlogfile" "$msg"
        fi

     fi

     if [ "${mdl}" = "gfs" ]; then
       INIT=0
     else
       INIT=
     fi
 
     let loop=${loop}+1
  done

  cd $DATA
  exit
