#!/bin/ksh
######################################################################
#  UNIX Script Documentation Block
#                      .
# Script name:         verif_gridtobs_aqmmax.sh
# Script description:  Run max (04z-04z) ozone verification for CMAQ
#
# Author:      Marina Tsidulko     Org: NP22       Date: 2006-02-08
#
# Abstract: This script runs verification for max ozone concentrations
#           for CMAQ both for 1hr max and 8hr max
#
# Script history log:
# 2006-02-08    Marina Tsidulko
# 2008-08-04    Julia Zhu
#               Modification for production implementation
######################################################################
set -xa
msg="JOB $job HAS BEGUN"
postmsg "$jlogfile" "$msg"

model_p="aqm"
cmaq_domain="cmaq5x"
#regions="ozonemax pmmax pmave"
regions="ozonemax"

vdaym1=`/nwprod/util/exec/ndate -24 $vdate |cut -c1-8`
vdayp1=`/nwprod/util/exec/ndate +24 $vdate |cut -c1-8`
vdayp2=`/nwprod/util/exec/ndate +48 $vdate |cut -c1-8`
vdatep1=`/nwprod/util/exec/ndate +24 $vdate`

if [ $SENDCOM = YES ]
then
  if [ ! -s $COMVSDB/${model_p} ]; then mkdir -p $COMVSDB/${model_p}; fi
  if [ -s $COMVSDB/${model_p}/${cmaq_domain}max_${vday}.vsdb ]
  then
    sed -e "/$vday$vcyc/d" $COMVSDB/${model_p}/${cmaq_domain}max_${vday}.vsdb >$COMVSDB/${model_p}/${cmaq_domain}max_${vday}.vsdb1
    mv $COMVSDB/${model_p}/${cmaq_domain}max_${vday}.vsdb1 $COMVSDB/${model_p}/${cmaq_domain}max_${vday}.vsdb
  fi
fi

for field in $regions
do
  case $field in
    ozonemax) ver_grid="148"
              filnam="aqm.t12z.awpozcon"
              filbufr="prepbufr.tm00"
              avg_hr=24
              COMBUFR_IN1=$COMBUFR/hourly.$vday
              COMBUFR_IN2=$COMBUFR/hourly.$vdayp1
              network="ozone"
              maxgrib="maxgrib"
              XC="_ozone";;
   pmave)     ver_grid="148"
              filnam="aqm.t06z.25pm"
              filbufr="anowpm.pb.tm024"
              avg_hr=30
              COMBUFR=/stmp/wx20wh/CHKOUT_TMP/com/hourly/prod
              INDIR=/com/${NET}/para/${RUN}
              COMBUFR_IN1=$COMBUFR/hourly.$vdayp1
              COMBUFR_IN2=$COMBUFR/hourly.$vdayp2
              network="pm"
              maxgrib="avegrib"
              XC="_pm";;
  pmmax)      ver_grid="148"
              filnam="aqm.t06z.25pm"
              filbufr="anowpm.pb.tm024"
              avg_hr=30
              COMBUFR=/stmp/wx20wh/CHKOUT_TMP/com/hourly/prod
              INDIR=/com/${NET}/para/${RUN}
              COMBUFR_IN1=$COMBUFR/hourly.$vdayp1
              COMBUFR_IN2=$COMBUFR/hourly.$vdayp2
              network="pm"
              maxgrib="maxgrib"
              XC="_pm";;
  esac

  MODNAM=`echo $cmaq_domain | tr '[a-z]' '[A-Z]'`

  # ---------------------------------
  # Construct the keeplist parm card:
  # ---------------------------------
  rm -rf gridtobs.keeplist.${field}
  cp $PARMverf_gridtobs/verf_gridtobs.keeplist gridtobs.keeplist

  cat gridtobs.keeplist |while read line
  do
    net_name=`echo $line |awk -F"|" '{print $1}'`
    if [ $net_name = $network ]
    then
      GRID_NUM=`echo $line |awk -F"|" '{print $2}'`
      TIME_WIN=`echo $line |awk -F"|" '{print $3}'`
      OBTYP=`echo $line |awk -F"|" '{print $4}'`
      break
    fi
  done

  TIME_WIN=${vdate}

  echo "IRETGRID     - GRID NUMBER OF THE RETENTION AREA" >gridtobs.keeplist.${field}
  echo $GRID_NUM >>gridtobs.keeplist.${field}
  echo "YYMMDD       - DATE OR TIME WINDOW INDICATOR" >>gridtobs.keeplist.${field}
  echo $TIME_WIN >>gridtobs.keeplist.${field}
  echo "OBTYP        - UP TO 20 OB TYPES TO BE RETAINED" >>gridtobs.keeplist.${field}
  for obstyp in $OBTYP
  do
    echo $obstyp >>gridtobs.keeplist.${field}
  done

  # ------------------------
  # Create LEVCAT parm file:
  # ------------------------
  cp $PARMverf_gridtobs/verf_gridtobs.levcat gridtobs.levcat

  cat gridtobs.levcat |while read tmp
  do
    levcat_domain=`echo $tmp |awk -F"|" '{print $1}'`
    if [ $levcat_domain = $field ]
    then
      NUMLEV=`echo $tmp |awk -F"|" '{print $2}'`
      FIT=`echo $tmp |awk -F"|" '{print $3}'`
      break
    fi
  done

cat <<EOF_LEVCAT >gridtobs.levcat.${network}
 &LEVCAT
 NUMLEV=$NUMLEV
 FIT=$FIT
 /
EOF_LEVCAT

  typeset -Z2 fhr

  # -------------------------------
  # Start the calculation from here
  # -------------------------------
  for cmaqday in DAY1 DAY2
  do
    case $cmaqday in
      DAY1)if [ $field = "ozonemax" ]
           then
             hourlist1="17 18 19 20 21 22 23 24 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16"
             hourlist8="24 25 26 27 28 29 30 31 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23"
             cutoff_h="16"
             FHR=24
           elif [ $field = "pmave" -o $field = "pmmax" ]
           then
             hourlist1="23 24 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22"
             hourlist8=""
             cutoff_h="22"
             FHR=30
           fi
           ;;
    DAY2)if [ $field = "ozonemax" ]
         then
           hourlist1="17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40"
           hourlist8="24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47"
           FHR=48
         elif [ $field = "pmave" -o $field = "pmmax" ]
         then
           hourlist1="23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46"
           hourlist8=""
           FHR=54
         fi
         ;;
    esac

    rm -rf AWIP* input_*

    for fhr in $hourlist1
    do
      if [ $cmaqday = "DAY1" -a $fhr -le $cutoff_h ]
      then
        cp ${INDIR}.$vday/${filnam}${fhr} AWIP1_${fhr}.tm00
      else
        cp ${INDIR}.$vdaym1/${filnam}${fhr} AWIP1_${fhr}.tm00
      fi
      $utilexec/grbindex AWIP1_${fhr}.tm00 AWIP1_${fhr}i.tm00  
    done

    for fhr in $hourlist8
    do
      cp ${INDIR}.$vdaym1/${filnam}${fhr} AWIP8_${fhr}.tm00
      $utilexec/grbindex AWIP8_${fhr}.tm00 AWIP8_${fhr}i.tm00
    done
  
    # ------------------------------------------------------
    #  Make an ordered list of forecast files to fit to data
    # ------------------------------------------------------
    j=1
    rm -rf input_hour
    while [ $j -le 24 ]
    do
      fhr1=`echo $hourlist1 |cut -d" " -f${j}'`
      fhr8=`echo $hourlist8 |cut -d" " -f${j}'`

      if [ $field = "ozonemax" ]
      then
cat<<eof>>input_hour
CMAQ     AWIP1_${fhr1}.tm00        AWIP8_${fhr8}.tm00
CMAQ     AWIP1_${fhr1}i.tm00       AWIP8_${fhr8}i.tm00
eof
      elif [ $field = "pmave" -o $field = "pmmax" ]
      then
cat<<eof>>input_hour
CMAQ     AWIP1_${fhr1}.tm00
CMAQ     AWIP1_${fhr1}i.tm00
eof
      fi
      let "j=j+1" 
    done

    # -----------------------------------------
    # Run max_grib to obtain the maximum value
    # -----------------------------------------
    export pgm=verf_gridtobs_maxgrib
    . prep_step
 
    startmsg
    $EXECverf_gridtobs/verf_gridtobs_${maxgrib}${XC} <input_hour >maxgrib_${field}_${cmaqday}.out
    export err=$?; err_chk

    # Input hour for max
    cp outgribmax AWIP${avg_hr}.tm00
    $utilexec/grbindex AWIP${avg_hr}.tm00 AWIP${avg_hr}i.tm00

cat<<eof>input_hour_max
CMAQ     AWIP${avg_hr}.tm00
CMAQ     AWIP${avg_hr}i.tm00
eof

    # -----------------------------------------------
    # Create the input parm card to gridtobs program
    # -----------------------------------------------
    cat $PARMverf_gridtobs/verf_gridtobs.${field}\
    | sed -e s/MODEL_HOUR/$FHR/g -e "s/MODNAM/$MODNAM/g" -e "s/GRDNUM/$ver_grid/g" > gridtobs_${field}1
    mv gridtobs_${field}1 gridtobs_${field}_${cmaqday}

    # define a prepbufr file to filter and fit
    cp $COMBUFR_IN1/aqm.t12z.${filbufr} prepda.${vdate}
    cp $COMBUFR_IN2/aqm.t12z.${filbufr} prepda.${vdatep1}

    # ---------------------------------------------------------------
    #  run editbufr and prepfits on the combined set of observations
    # ---------------------------------------------------------------
    rm prepfits.${field}.${vdate}_$cmaqday
 
    export pgm=verf_gridtobs_editbufr
    . prep_step

    export XLFUNIT_20=prepda.${vdate}
    export XLFUNIT_21=prepda.${vdatep1}
    export XLFUNIT_22=$PARMverf_gridtobs/verf_gridtobs.prepfits.tab_${network}
    export XLFUNIT_70=bufrout_${field}

    startmsg
    $EXECverf_gridtobs/verf_gridtobs_editbufr${XC}max < gridtobs.keeplist.${field} >>editbufr_${field}_${cmaqday}.out
    export err=$?; err_chk

    # ---------------------
    # Run prepfits step
    # ---------------------

    export pgm=verf_gridtobs_prepfits
    . prep_step

    export XLFUNIT_11=gridtobs.levcat.${network}
    export XLFUNIT_20=bufrout_${field}
    export XLFUNIT_22=$PARMverf_gridtobs/verf_gridtobs.prepfits.tab_${network}
    export XLFUNIT_50=prepfits.${field}.${vdate}_${cmaqday}
    export XLFUNIT_101=airnow1_list
    export XLFUNIT_108=airnow8_list

    startmsg
    $EXECverf_gridtobs/verf_gridtobs_prepfits${XC} < input_hour_max >>prepfits_${field}_${cmaqday}.out
    export err=$?; err_chk

    if [ $SENDCOM = YES ]
    then
      cp prepfits.${field}.${vdate}_${cmaqday} $COMOUT/aqmmax_prefits.${field}.${cmaqday}
      cp airnow1_list       ${COMOUT}/${cmaq_domain}_airnow1_list${field}.${cmaqday}
      cp airnow8_list       ${COMOUT}/${cmaq_domain}_airnow8_list${field}.${cmaqday}
      cp outgribmax ${COMOUT}/${cmaq_domain}_${field}.${cmaqday}
    fi
  
    # ----------------------
    # Run gridtobs step
    # ----------------------
    pgm=verf_gridtobs_gridtobs
    . prep_step

    export XLFUNIT_10=prepfits.${field}.${vdate}_${cmaqday}
    export XLFUNIT_20=$PARMverf_gridtobs/verf_gridtobs.grid104
    export XLFUNIT_21=$PARMverf_gridtobs/verf_gridtobs.regions
    export XLFUNIT_50=${field}_${vdate}_${cmaqday}.vdb

    startmsg
    $EXECverf_gridtobs/verf_gridtobs_gridtobs${XC} <gridtobs_${field}_${cmaqday} >gto_${field}_${cmaqday}.out
    export err=$?; err_chk

    cat ${field}_${vdate}_${cmaqday}.vdb >>${field}_${vdate}.vsdb

  done  # cmaqday

done  #field

# -------------------------------
# Save the output and vsdb files
# -------------------------------
if [ $SENDCOM = YES ]
then
  for field in $regions
  do
    cat ${field}_${vdate}.vsdb >>$COMVSDB/${model_p}/${cmaq_domain}max_${vday}.vsdb
  done

  ## DBN alert the vsdb record files to TOC:
  if [ $SENDDBN = YES ]
  then
    $DBNROOT/bin/dbn_alert MODEL VERIF_GRID2OBS $job $COMVSDB/${model_p}/${cmaq_domain}max_${vday}.vsdb
  fi
fi

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

msg='JOB $job HAS COMPLETED NORMALLY.'
postmsg "$jlogfile" "$msg"

############## END OF SCRIPT #######################
