#!/bin/ksh
####################################################################################
# Name of script:    verf_precip_getpptfcst.sh.sms
# Purpose of script: This script extracts the precip data from the model forecast
#                    outputs it in the format of $model_$yyyy$mm$dd$hh_$hr1_$hr2
#                    where hr1 and hr2 (3-digit) are the beginning and ending time of
#                    the accumulation period.
# History:
#
# Usage:  verf_precip_getpptfcst.sh.sms $input_card
#         where in line 1 of the input_card:
#             arg1: model name (e.g. nam)
#             arg2: convert? (e.g. in GFS/MRF, will convert rain rate to rain accum)
#             arg3: parameter name (normally '061', for GFS is 059, ECMWF is 228)
#
######################################################################################
set -x

INPUT=$1
set -A line1 `sed -n 1p $INPUT`
model=${line1[0]}

if [ ${#line1[@]} -gt 1 ]; then    # We will do 'convert'.
  if [ ${line1[1]} = convert ]; then
     convert=yes
     mkdir $DATA/$model
  elif [ ${line1[1]} = gc ]; then
     convert=no
     gridconv=yes
  else
     echo 'Unrecognized convert option.  STOP.'
     exit
  fi
else
  convert=no
fi   # Finished processing the input 'convert' argument

if [ ${#line1[@]} -gt 2 ]; then
  parm=${line1[2]}
else
  parm=061
fi

typeset -Z3 grid parm fhr0 fhr1 fhr2 fhr3 tabl
#fhr3 is the 3-digit version of fhr, to be placed in cntrlfile

grid=`sed -n 2p $INPUT`
OUTFILE=$COMOUT`sed -n 4p $INPUT`
cycles=`sed -n 5p $INPUT`
fcsthrs=`sed -n 6p $INPUT`

if [ $convert = yes ]; then
  OUTFILE1=$OUTFILE
  OUTF=`echo $OUTFILE | nawk -F "/" '{print $NF}'`
  OUTDIR=`echo $OUTFILE | sed s/"\/\$OUTF//`
  OUTFILE=$DATA/$model/tmp_$OUTF
  if [ $model = ecmwf ]; then
    ECOUTPFIX=$OUTFILE
  fi
fi

for cyc in $cycles
do
   for fhr in $fcsthrs
   do
      fhr3=$fhr
      INFILE=`sed -n 3p $INPUT | sed s/%{cyc}%/$cyc/g | sed s/%{fhr}%/$fhr/g`
      if [ ! -s $INFILE ]; then
          echo $INFILE n/a >> $LOG
      fi

      if [ $model = jma ]; then
          tabl=3
      elif [ $model = ukmo ]; then
          tabl=1
      else
          tabl=2
      fi

      # do not use 'brkout' for ecmwf.  Also remember that we are dealing with 
      # daym1 for ecmwf.
      if [ $model = ecmwf ]; then  
         OUTFILE=${ECOUTPFIX}${daym1}${cyc}_000_${fhr3}
         
         export pgm=verf_precip_pcpconform
         . prep_step

         $EXECverf_precip/verf_precip_pcpconform ecmwf $INFILE $OUTFILE >>$pgmout
         export err=$?; err_chk
      else 
         cat > cntrlfile << EOF
INPUTF  A120 :($INFILE
KGTYPE  I5   :(${grid})
OTPUTF  A120 :($OUTFILE
TABLE I3:($tabl)  PARM I3:($parm)  TFLAG I2:(-1)  P1 I3:( -1)  P2 I3:(${fhr3})
----:----|----:----|----:----|----:----|----:----|----:----|----:----|----:---
EOF
         export pgm=verf_precip_brkout_fcst
         . prep_step

         $EXECverf_precip/verf_precip_brkout_fcst < cntrlfile >> $pgmout
         export err=$?; err_chk

      fi     

   done  # end of the fhr loop
done     # end of the cyc loop

# put fcsthrs in an array 'afcsthrs so we can refer to the individual 
# elements by their indices.
# e.g. fcsthrs="12 24 36 48"
# then ${afcsthrs[0]}=12
#      ${afcsthrs[1]}=24
#      ${afcsthrs[2]}=36
#      ${afcsthrs[3]}=48
#      ${#afcsthrs[@]}=4 (number of array elements)

set -A afcsthrs $fcsthrs

mod3=`echo $model | cut -c 1-3`
if [ $mod3 = gec -o $mod3 = gep -o $mod3 = gen ]
then
   mod3=gef
fi

if [ $convert = yes ]; then
  cd $DATA/$model
  /nwprod/util/ush/setup.sh
#
  if [[ $model = ecmwf || $model = jma ]]; then
    if [ $model = ecmwf ]; then
      daysub=$daym1
    elif [ $model = jma ]; then
      daysub=$day
    fi

    for cyc in $cycles
    do
      let "index=${#afcsthrs[@]}-1"
      while [ $index -gt 0 ]; do  # process array elements N-1, N-2, ..., 1
        let "indexm1=$index-1"
        fhr2=${afcsthrs[$index]}
        fhr1=${afcsthrs[$indexm1]}
        cat > input_subtract << EOF
mod
$OUTDIR/${model}_
tmp_${model}_${daysub}${cyc}_000_${fhr1}
tmp_${model}_${daysub}${cyc}_000_${fhr2}
EOF
        pgm=verf_precip_diffpcp
        . prep_step

        $EXECverf_precip/verf_precip_diffpcp < input_subtract >$pgmout
        export err=$?; err_chk

        let "index=$index-1"
      done                        # process array elements N-1, N-2, ..., 1
# For the first (i.e. array element 0) file, just copy over:
      fhr0=${afcsthrs[0]}
      cp    tmp_${model}_${daysub}${cyc}_000_${fhr0} \
        $OUTDIR/${model}_${daysub}${cyc}_000_${fhr0}
    done  # cyc

  elif [[ $mod3 = gfs || $mod3 = gef || $model = ukmo || $mod3 = wrf ]]
  then
      
    if [ $mod3 = gef ]; then
      model_1=gfs
    else
      model_1=$model
    fi

    ls -1 tmp_* | sed s/tmp_//g > list
    for file in `cat list`
    do
      pgm=verf_precip_pcpconform
      . prep_step

      $EXECverf_precip/verf_precip_pcpconform $model_1 tmp_$file $OUTDIR/$file >>$pgmout
      export err=$?; err_chk
    done

  fi # different 'convert' for different models
fi   # convert?

# 
# If gridconv=yes, we are extracting grid/convective scale model output
# separately, gridscale (parm=62) first, convective scale (parm=63) next.  If
# the 'model name' here ends with 'c', that means the grid scale field
# has already been extracted.  Add them together here.  
#

echo 'gridconv=' $gridconv

if [ $gridconv = yes ]; then
# find out whether the precip type is 'c' or 'g'. 
  typeset -R1 ptype
  ptype=$model

  if [ $ptype = c ]; then
    mod2=$model
    mod1=`echo $model | sed 's/c$/g/'` # replace last 'c' with 'g'
    mod=`echo $model | sed 's/c$//'`  # remove last 'c'

    for file1 in `ls -1 $COMOUT$day/${mod1}_*`
    do 
      file2=`echo $file1 | sed 's/'$mod1'/'$mod2'/'`
      filetot=`echo $file1 | sed 's/'$mod1'/'$mod'/'`
     
      if [ -s $file1 -a -s $file2 ]; then
        cat > input_combgrdcnvpcp <<EOF
$file1
$file2
$filetot
EOF
      $EXECverf_precip/verf_precip_addgrdcnv < input_combgrdcnvpcp

      fi # if both gridscale and conv files exist

    done # finished adding up gridscale and convective precip for total precip
         # for a particular model  
  fi # $ptype = c
fi   # $gridconv = yes 

exit



