#!/bin/ksh

set -x


typeset -Z2 narre_cyc
narre_cyc=$cyc

mkdir -p $DATA_IN/datadone

#for grid in 130 242 ; do 
grid=$1

typeset -Z2 HH
typeset -Z2 HH1

echo 'narre_cyc:' $PDY$narre_cyc 

for time in 0 1 2 3 4 5 6 ; do

  RAP_YMDH=` /nwprod/util/exec/ndate -$time ${PDY}${narre_cyc}`
  RAP_dir=`echo $RAP_YMDH | cut -c 1-8`
  RAP_cyc=`echo $RAP_YMDH | cut -c 9-10`
  echo '  Day ' $RAP_dir 'RAP_cyc ' $RAP_cyc

  if [ ${grid} = '130' ] ; then
    RAP_head=$RAPprod/rap.${RAP_dir}/rap.t${RAP_cyc}z.awp${grid}pgrbf
  elif [ ${grid} = '242' ] ; then
    RAP_head=$RAPprod/rap.${RAP_dir}/rap.t${RAP_cyc}z.awp${grid}f
  fi

    scrub1=${DATA_IN}/scrub1_$grid/narre.${RAP_dir}
    scrub2=${DATA_IN}/scrub2_$grid/narre.${RAP_dir}

  if [ ! -d $scrub1 ] ; then
    mkdir -p $scrub1
  fi

  if [ ! -d $scrub2 ] ; then
    mkdir -p $scrub2
  fi

  for fhr in 1 2 3 4 5 6 7 8 9 10 11 12; do
   HH=`expr $fhr + $time` 
   RAP_grib2=${RAP_head}${HH}
   RAP_grib1=$scrub2/rap.t${RAP_cyc}z.pgrb${grid}.f${HH}

   if [ -s $RAP_grib2 ] ; then
     if [ ! -s $RAP_grib1 ] ; then     
       cp $RAP_grib2 $RAP_grib1
       cd $scrub2
       echo rap.t${RAP_cyc}z.pgrb${grid}.f${HH} ${grid}|$EXECnarre/narre_cat
       cat $RAP_grib1 >> $scrub1/rap.t${RAP_cyc}z.pgrb${grid}.f${HH}
       cat rap.t${RAP_cyc}z.pgrb${grid}.f${HH}.out >> $scrub1/rap.t${RAP_cyc}z.pgrb${grid}.f${HH}
       rm -f rap.t${RAP_cyc}z.pgrb${grid}.f${HH}.out

       #### split 1hr precip data from $RAP_grib1
       HH1=`expr $HH - 1`
       echo rap.t${RAP_cyc}z.pgrb${grid}.f${HH1} rap.t${RAP_cyc}z.pgrb${grid}.f${HH} $RAP_cyc $HH1 $HH ${grid}|$EXECnarre/narre_precip
       cat rap.t${RAP_cyc}z.pgrb${grid}.f${HH}.prcp >> $scrub1/rap.t${RAP_cyc}z.pgrb${grid}.f${HH}
       rm -f rap.t${RAP_cyc}z.pgrb${grid}.f${HH}.prcp

     else
       echo $RAP_grib1 ' already existing!'
     fi 
    else
     echo $RAP_grib2 ' not existing, skip it!'
    fi

  done   # done for times 

done     # done for fhr

    echo 'Done for RAP cyc ' $cyc ' grid' $grid  >> $DATA_IN/datadone/done4RAPcyc${cyc}grid$grid

    ls -l $DATA_IN/datadone/done4RAPcyc${cyc}grid$grid

#done     # done for grid
