#!/bin/ksh

##########################################################################
####  UNIX Script Documentation Block                                    #
#                                                                        #
# Script name:         rtma_getguess.sh                                  #
# Script description:  Read in first guess in grib1 as created by the RAP#
#                      post and reformat to conform to GSI requirements. #
#                      Read also the prepbufr file that contains the obs #                      
#                                                                        #
# Author:      Manuel Pondeca        Org: NP22         Date: 2005-10-30  #
#                                                                        #
# Script history log:                                                    #
# 2005-10-30  Manuel Pondeca                                             #
#                                                                        #
##########################################################################
set -x

cd $DATA
                                                                                    
msg="HAS BEGUN on `hostname`"
postmsg "$jlogfile" "$msg"
                                                                                    
CDATE=$PDY$cyc
##########################################################################
##########################################################################
   icgespath=${icgespath:-$COM}   # path for the FGAT guess files

   CYCLEm1=`/nwprod/util/exec/ndate -01 $CDATE`
   YYYYMMDDm1=`echo ${CYCLEm1} | cut -c 1-8`
   HHm1=`echo ${CYCLEm1} | cut -c 9-10`
   GESDIRm1=$icgespath/rtma2p5.${YYYYMMDDm1}

   CYCLEm2=`/nwprod/util/exec/ndate -02 $CDATE`
   YYYYMMDDm2=`echo ${CYCLEm2} | cut -c 1-8`
   HHm2=`echo ${CYCLEm2} | cut -c 9-10`
   GESDIRm2=$icgespath/rtma2p5.${YYYYMMDDm2}

   CYCLEm3=`/nwprod/util/exec/ndate -03 $CDATE`
   YYYYMMDDm3=`echo ${CYCLEm3} | cut -c 1-8`
   HHm3=`echo ${CYCLEm3} | cut -c 9-10`
   GESDIRm3=$icgespath/rtma2p5.${YYYYMMDDm3}

   CYCLEm4=`/nwprod/util/exec/ndate -04 $CDATE`
   YYYYMMDDm4=`echo ${CYCLEm4} | cut -c 1-8`
   HHm4=`echo ${CYCLEm4} | cut -c 9-10`
   GESDIRm4=$icgespath/rtma2p5.${YYYYMMDDm4}


   rappath=${COMRAP:-/com/rap/prod}
###################################################################################
# Get the ndfd guess file, which is the downscaled 1h-RAP
# forecast from the previous hour
###################################################################################
   found_rapges=no
   ic=1
   while [ $ic -le 6 ] ; do
     typeset -2Z RAPFHH
     RAPFHH=$ic
     RAPCYCLE=`/nwprod/util/exec/ndate -$RAPFHH $CDATE`
     RAPPDY=`echo $RAPCYCLE |cut -c1-8`
     RAPCC=`echo $RAPCYCLE |cut -c9-10`

     if [ -s $rappath/rap.${RAPPDY}/rap.t${RAPCC}z.smartrapconus${RAPFHH} ]; then
         infile_g187=$rappath/rap.${RAPPDY}/rap.t${RAPCC}z.smartrapconus${RAPFHH}
         echo "export RAPCYCLE=$RAPCYCLE" >> $COMOUT/rtma2p5.t${cyc}z.envir.sh
         echo "export RAPFHH=$RAPFHH" >> $COMOUT/rtma2p5.t${cyc}z.envir.sh
         found_rapges=yes
        break
     else
        let "ic=ic+1"
      fi
   done

   if [[ ${found_rapges} = no ]] ; then
       echo 'No NDFD guess available - exiting'
       exit 0
   fi
###################################################################################
#
###################################################################################
#==> RETRIEVE THE OFF-TIME FIRST GUESS FIELDS FOR USE WITH FGAT
###################################################################################

   pathminus1h[1]=$GESDIRm1                       ; fminus1h[1]=${RUN}.t${HHm1}z.2dvaranl_ndfd.grb1
   pathminus1h[2]=$rappath/rap.${YYYYMMDDm1}      ; fminus1h[2]=rap.t${HHm1}z.smartrapconusanl
   pathminus1h[3]=$rappath/rap.${YYYYMMDDm2}      ; fminus1h[3]=rap.t${HHm2}z.smartrapconus01

   tminus1h[1]=${CYCLEm1}anl
   tminus1h[2]=${CYCLEm1}anl
   tminus1h[3]=${CYCLEm2}f01


   nsearch=3
   foundminus1h=no

   it=1
   while [ $it -le $nsearch ] ; do
      if [ -s ${pathminus1h[$it]}/${fminus1h[$it]} ] ; then
         pathminus1h=${pathminus1h[$it]}
         fminus1h=${fminus1h[$it]}
         tminus1h=${tminus1h[$it]}
         if (( $it == 1 )) ; then
            gridid[2]=184
           else
            gridid[2]=187
         fi
         echo "export CDATEgesm1=$tminus1h" >> $COMOUT/rtma2p5.t${cyc}z.envir.sh
         foundminus1h=yes
         break
      fi
      let "it=it+1"
   done

                                ##################################
                                ##################################

   pathminus2h[1]=$GESDIRm2                       ; fminus2h[1]=${RUN}.t${HHm2}z.2dvaranl_ndfd.grb1
   pathminus2h[2]=$rappath/rap.${YYYYMMDDm2}      ; fminus2h[2]=rap.t${HHm2}z.smartrapconusanl
   pathminus2h[3]=$rappath/rap.${YYYYMMDDm3}      ; fminus2h[3]=rap.t${HHm3}z.smartrapconus01

   tminus2h[1]=${CYCLEm2}anl
   tminus2h[2]=${CYCLEm2}anl
   tminus2h[3]=${CYCLEm3}f01


   nsearch=3
   foundminus2h=no

   it=1
   while [ $it -le $nsearch ] ; do
      if [ -s ${pathminus2h[$it]}/${fminus2h[$it]} ] ; then
         pathminus2h=${pathminus2h[$it]}
         fminus2h=${fminus2h[$it]}
         tminus2h=${tminus2h[$it]}
         if (( $it == 1 )) ; then
           gridid[4]=184
          else
           gridid[4]=187
         fi
         echo "export CDATEgesm2=$tminus2h" >> $COMOUT/rtma2p5.t${cyc}z.envir.sh 
         foundminus2h=yes
         break
      fi
      let "it=it+1"
   done

                                ##################################
                                ##################################

   pathminus3h[1]=$GESDIRm3                       ; fminus3h[1]=${RUN}.t${HHm3}z.2dvaranl_ndfd.grb1
   pathminus3h[2]=$rappath/rap.${YYYYMMDDm3}      ; fminus3h[2]=rap.t${HHm3}z.smartrapconusanl
   pathminus3h[3]=$rappath/rap.${YYYYMMDDm4}      ; fminus3h[3]=rap.t${HHm4}z.smartrapconus01

   tminus3h[1]=${CYCLEm3}anl
   tminus3h[2]=${CYCLEm3}anl
   tminus3h[3]=${CYCLEm4}f01


   nsearch=3
   foundminus3h=no

   it=1
   while [ $it -le $nsearch ] ; do
     if [ -s ${pathminus3h[$it]}/${fminus3h[$it]} ] ; then
         pathminus3h=${pathminus3h[$it]}
         fminus3h=${fminus3h[$it]}
         tminus3h=${tminus3h[$it]}
         if (( $it == 1 )) ; then
           gridid[5]=184
          else
           gridid[5]=187
         fi
         echo "export CDATEgesm3=$tminus3h" >> $COMOUT/rtma2p5.t${cyc}z.envir.sh
         foundminus3h=yes
         break
      fi
      let "it=it+1"
   done

                                ##################################
                                ##################################

   pathplus1h[1]=$rappath/rap.${PDY}              ; fplus1h[1]=rap.t${cyc}z.smartrapconus01
   pathplus1h[2]=$rappath/rap.${YYYYMMDDm1}       ; fplus1h[2]=rap.t${HHm1}z.smartrapconus02

   tplus1h[1]=${CDATE}f01
   tplus1h[2]=${CYCLEm1}f02


   nsearch=2
   foundplus1h=no

   it=1
   while [ $it -le $nsearch ] ; do
      if [ -s ${pathplus1h[$it]}/${fplus1h[$it]} ] ; then
         pathplus1h=${pathplus1h[$it]}
         fplus1h=${fplus1h[$it]}
         tplus1h=${tplus1h[$it]}
         gridid[3]=187
         echo "export CDATEgesp1=$tplus1h" >> $COMOUT/rtma2p5.t${cyc}z.envir.sh
         foundplus1h=yes
         break
      fi
      let "it=it+1"
   done

   usefgat=.true.
   if [[ ${foundminus1h} = no || ${foundminus2h} = no || ${foundminus3h} = no || \
         ${foundplus1h} = no ]] ; then

      echo "missing at least one off-time first guess. proceed without FGAT"
      usefgat=.false.
   fi
   echo "export usefgat=$usefgat" >> $COMOUT/rtma2p5.t${cyc}z.envir.sh


   set +x
   echo 'foundminus1h '$foundminus1h
   echo 'foundplus1h  '$foundplus1h
   echo 'foundminus2h '$foundminus2h
   echo 'foundminus3h '$foundminus3h
   echo 'usefgat      '$usefgat
   set -x
###################################################################################
#
###################################################################################
# COPY ALL GUESS FILES OVER TO THE WORKING DIRECTORY
###################################################################################
   infile=rap.guess.${CDATE}
   /nwprod/util/exec/copygb -g184 -x $infile_g187 $infile

   if [[ "$usefgat" = ".true." ]] ; then
      infile2=fguess_minus1.${CDATE}
      cp ${pathminus1h}/${fminus1h} $infile2

      infile3=fguess_plus1.${CDATE}
      cp ${pathplus1h}/${fplus1h}   $infile3

      infile4=fguess_minus2h.${CDATE}
      cp ${pathminus2h}/${fminus2h} $infile4

      infile5=fguess_minus3h.${CDATE}
      cp ${pathminus3h}/${fminus3h} $infile5

   fi
###################################################################################
#
###################################################################################
# RETRIEVE THE BIAS CORRECTION FIELD
###################################################################################
  CDATEm24=`/nwprod/util/exec/ndate -24 $CDATE`
  lstats_date=`echo $CDATEm24 |cut -c1-8`
  cp $icgespath/rtma2p5.${lstats_date}/rtma_biascor_out.dat_$CDATEm24 rtma_biascor_in.dat 
  err1=$?
  if (( $err1 != 0 )) ; then
     echo "Could not find the bias correction field. Proceed without bias correction"
   fi
###################################################################################
#
###################################################################################
#**********************************************************************************
# RETRIEVE THE OBSERVATION REJECT LISTS
#**********************************************************************************
   cp $FIXrtma/rtma2p5_bigrjlist.txt bigrjlist.txt 

   pdy0=`echo $CYCLEm1 | cut -c1-8`
   gesdir0=$gespath/rtma2p5.${pdy0}

   cp ${gesdir0}/t_rjlist.txt_dynamic_$CYCLEm1    t_rjlist.txt_dynamic
   cp ${gesdir0}/q_rjlist.txt_dynamic_$CYCLEm1    q_rjlist.txt_dynamic
   cp ${gesdir0}/p_rjlist.txt_dynamic_$CYCLEm1    p_rjlist.txt_dynamic
## cp ${gesdir0}/w_rjlist.txt_dynamic_$CYCLEm1    w_rjlist.txt_dynamic

###################################################################################


# write out records from grib file in binary format
# with header (http://www.cpc.ncep.noaa.gov/products/wesley/wgrib.html)

# write out fields in the order specified in varname_2d_ndfd of NDFDgrid.f

wgrib=/nwprod/util/exec/wgrib

rm -f slabs.dat
$wgrib -s $infile | grep ":PRES:sfc:" | $wgrib -i $infile         -o slabs.dat
$wgrib -s $infile | grep ":HGT:sfc:"  | $wgrib -i $infile -append -o slabs.dat
$wgrib -s $infile | grep ":TMP:sfc:"  | $wgrib -i $infile -append -o slabs.dat
$wgrib -s $infile | grep ":DPT:sfc:"  | $wgrib -i $infile -append -o slabs.dat
$wgrib -s $infile | grep ":UGRD:sfc:" | $wgrib -i $infile -append -o slabs.dat
$wgrib -s $infile | grep ":VGRD:sfc:" | $wgrib -i $infile -append -o slabs.dat
$wgrib -s $infile | grep ":SPFH:sfc:" | $wgrib -i $infile -append -o slabs.dat
$wgrib -s $infile | grep ":PRES:sfc:" | $wgrib -i $infile -append -o slabs.dat #dummy field
$wgrib -s $infile | grep ":PRES:sfc:" | $wgrib -i $infile -append -o slabs.dat #dummy field
$wgrib -s $infile | grep ":PRES:sfc:" | $wgrib -i $infile -append -o slabs.dat #dummy field
###################################################################################

###################################################################################
# compile and run program that outputs first guess in the binary format
# required by the GSI-2DVAR. 

cat << EOF > gridname_input
&gridname
    cgrid='cohres',
    lbiascor=.true.
    lpbiascor=.false.,
    pbiascor=0.0,
    ltbiascor=.true.,
    tbiascor=0.1,
    lqbiascor=.false.,
    qbiascor=0.0,
    lubiascor=.false.,
    ubiascor=0.0,
    lvbiascor=.false.,
    vbiascor=0.0,
    ltdbiascor=.false.,
    tdbiascor=0.0,
    mkrjlists=.true.,
    hwrfblend=.false.
/
EOF
#
cat << EOF > parm_ndfd_time_namelist
&timeinfo
    iyear=`echo $PDY |cut -c1-4`,
    imonth=`echo $PDY |cut -c5-6`,
    iday=`echo $PDY |cut -c7-8`,
    ihour=$cyc
/
EOF


   ln -s -f  parm_ndfd_time_namelist                    fort.9
   ln -s -f  slabs.dat                                  fort.20 
   ln -s -f  $FIXrtma/rtma2p5_latlon_mpfactor.dat      fort.30
   ln -s -f  $FIXrtma/rtma2p5_slmask.dat_nolakes_exp2ndfd  fort.40
   ln -s -f  twodvar_input_bi                           fort.88 # ndfd bckg converted 
#                                                                 to gsi format
   $EXECrtma/rtma2p5_firstguess >>$pgmout 2>errfile
   export err=$?; err_chk
   cat $pgmout

   if [ $SENDCOM = YES ]
   then
       cp twodvar_input_bi $COMOUT/${RUN}.t${cyc}z.2dvar_input
       cp slabs.dat  $COMOUT/${RUN}.t${cyc}z.slabs.dat
       cp slabs2.dat  $COMOUT/${RUN}.t${cyc}z.slabs2.dat
       cp slabs2_nobiasc.dat  $COMOUT/${RUN}.t${cyc}z.slabs2_nobiasc.dat
       cp $infile_g187 $COMOUT/${RUN}.t${cyc}z.smartrapconus01
       cp $infile $COMOUT/${RUN}.t${cyc}z.${infile}
       cp gridname_input $COMOUT/${RUN}.t${cyc}z.gridname_input
       cp t_rejectlist $COMOUT/${RUN}.t${cyc}z.t_rejectlist
       cp q_rejectlist $COMOUT/${RUN}.t${cyc}z.q_rejectlist
       cp p_rejectlist $COMOUT/${RUN}.t${cyc}z.p_rejectlist
       cp w_rejectlist $COMOUT/${RUN}.t${cyc}z.w_rejectlist
   fi



   if [[ "$usefgat" = ".true." ]] ; then

     foundges[2]=${foundminus1h}
     foundges[3]=${foundplus1h}
     foundges[4]=${foundminus2h}
     foundges[5]=${foundminus3h}

cat << EOF > gridname_input
&gridname
    cgrid='cohres',
    lbiascor=.false.,
    mkrjlists=.false.
/
EOF

     it=2
     while [ $it -le 5 ] ; do

       if [[ ${foundges[${it}]} = yes ]] ; then

          if [ $it -eq 2 ] ; then
             CYCLEFG=`/nwprod/util/exec/ndate -01 $CDATE`
             slabsfg=slabsm1.dat
             infilefg0=${infile2}
             suffix=m1
          fi

          if [ $it -eq 3 ] ; then
              CYCLEFG=`/nwprod/util/exec/ndate +01 $CDATE`
              slabsfg=slabsp1.dat
              infilefg0=${infile3}
              suffix=p1
          fi

          if [ $it -eq 4 ] ; then
              CYCLEFG=`/nwprod/util/exec/ndate -02 $CDATE`
              slabsfg=slabsm2.dat
              infilefg0=${infile4}
              suffix=m2
          fi

          if [ $it -eq 5 ] ; then
              CYCLEFG=`/nwprod/util/exec/ndate -03 $CDATE`
              slabsfg=slabsm3.dat
              infilefg0=${infile5}
              suffix=m3
          fi


cat << EOF > parm_ndfd_time_namelist${it}
&timeinfo
   iyear=`echo  ${CYCLEFG}  | cut -c 1-4`
   imonth=`echo ${CYCLEFG}  | cut -c 5-6`
   iday=`echo   ${CYCLEFG}  | cut -c 7-8`
   ihour=`echo  ${CYCLEFG}  | cut -c 9-10`
/
EOF

          /bin/rm -rf fort.9 fort.20 fort.30 fort.40 fort.88

          echo "gridid =" ${gridid[$it]}
          if [[ ${gridid[$it]} = 184 ]] ; then
             infilefg=${infilefg0}
             sfc0=''
            else
             /nwprod/util/exec/copygb -g184 -x ${infilefg0} ${infilefg0}_g184
             infilefg=${infilefg0}_g184
             sfc0='sfc:'
          fi

          rm -f $slabsfg
          $wgrib -s $infilefg | grep ":PRES:${sfc0}" | $wgrib -i $infilefg         -o $slabsfg
          $wgrib -s $infilefg | grep ":HGT:${sfc0}"  | $wgrib -i $infilefg -append -o $slabsfg
          $wgrib -s $infilefg | grep ":TMP:${sfc0}"  | $wgrib -i $infilefg -append -o $slabsfg
          $wgrib -s $infilefg | grep ":DPT:${sfc0}"  | $wgrib -i $infilefg -append -o $slabsfg
          $wgrib -s $infilefg | grep ":UGRD:${sfc0}" | $wgrib -i $infilefg -append -o $slabsfg
          $wgrib -s $infilefg | grep ":VGRD:${sfc0}" | $wgrib -i $infilefg -append -o $slabsfg
          $wgrib -s $infilefg | grep ":SPFH:${sfc0}" | $wgrib -i $infilefg -append -o $slabsfg
          $wgrib -s $infilefg | grep ":PRES:${sfc0}" | $wgrib -i $infilefg -append -o $slabsfg #dummy field
          $wgrib -s $infilefg | grep ":PRES:${sfc0}" | $wgrib -i $infilefg -append -o $slabsfg #dummy field
          $wgrib -s $infilefg | grep ":PRES:${sfc0}" | $wgrib -i $infilefg -append -o $slabsfg #dummy field


          ln -s -f  parm_ndfd_time_namelist${it}               fort.9
          ln -s -f  $slabsfg                                   fort.20
          ln -s -f  $FIXrtma/rtma2p5_latlon_mpfactor.dat      fort.30
          ln -s -f  $FIXrtma/rtma2p5_slmask.dat_nolakes_exp2ndfd  fort.40
          ln -s -f  twodvar_input_bi${it}                      fort.88 # ndfd bckg converted

          echo "*********************************" >>$pgmout 2>errfile
          echo "*********************************" >>$pgmout 2>errfile
          $EXECrtma/rtma2p5_firstguess >>$pgmout 2>errfile
          export err=$?; err_chk
          cat $pgmout

         if [ $SENDCOM = YES ]
         then
             cp twodvar_input_bi${it} $COMOUT/${RUN}.t${cyc}z.2dvar_input_bi${it}
             cp $slabsfg  $COMOUT/${RUN}.t${cyc}z.${slabsfg}
             cp slabs2.dat  $COMOUT/${RUN}.t${cyc}z.slabs2${suffix}.dat
             cp slabs2_nobiasc.dat  $COMOUT/${RUN}.t${cyc}z.slabs2${suffix}_nobiasc.dat
             cp $infilefg $COMOUT/${RUN}.t${cyc}z.${infilefg}
         fi

       fi

       let "it=it+1"
     done

     if [ $SENDCOM = YES ]
     then
         cp gridname_input $COMOUT/${RUN}.t${cyc}z.gridname_input_for_fgatofftimes
     fi
   fi

###################################################################################
msg='$job ENDED NORMALLY.'
postmsg "$jlogfile" "$msg"
############################ END OF SCRIPT ########################################
