#! /bin/sh
set +x
################################################################################
# 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.NAM
# 2nd - overwrite with +0 hour fields from current fcst (except ppt, fluxes)
#         cat DATA.NAM >> NAMA; rm DATA.NAM
# 3rd - write +3 hour fields to DATA.NAM
#         cat DATA.NAM >> NAMA
################################################################################
set -x

  tday=$1
  tcyc=$2


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

  for loop in 1 2 3 
  do
     if [ $loop -eq 1 ]
     then
      # cycle before $tday
        tmp=`/nwprod/util/exec/ndate -${CYC_INT} ${tday}${tcyc}`
        xcyc=`echo $tmp | cut -c9-10`
        xday=`echo $tmp | cut -c1-8`
        fhr=${CYC_INT}
     else
        xcyc=$tcyc
        xday=$tday
        if [ $loop -eq 2 ]
        then
           fhr="00"
        else
         # set fhr=FHR_INT, but make sure that there is a leading zero
           stg=${FHR_INT}
           indx=0
           while [ "$stg" != '' ];
           do
             stg=${stg#?}
             let indx=$indx+1
           done
           let len=$indx
           if [ $len -eq 1 ];then
             FHR_INT="0"${FHR_INT}
           fi
           fhr=${FHR_INT}
        fi
     fi

     NAMFILE=${COMNAMIN}/nam.${xday}/nam.t${xcyc}z.awphys${fhr}.tm00

     pgm=hysplit_nam12arl
     export pgm;. prep_step

     msg="hysplit_nam12arl for hour ${xday}${xcyc}F$fhr started"
     postmsg "$jlogfile" "$msg"

     $EXEChysplit/hysplit_nam12arl ${NAMFILE} >> $pgmout 2>errfile
     export err=$?;$DATA/err_chk

     if [ $loop -gt 1 ]
     then
        cat DATA.NAM >> NAMA
        rm DATA.NAM
     fi

  done

  cd $DATA
