#!/bin/ksh
######################################################################
####  UNIX Script Documentation Block
#                      .                                             .
# Script name:         exndas_h2obudget.sh
#             
# Script description:  Update the long-term precipitation budget array
#                      by comparing the hourly precipitation input for 
#                      the time period of ${TM48}-${TM24} 
#                      (where T0=$CYCLE=${day}12)
#                      i.e. the first 6 hours from NDAS cycles
#                           ${daym1}00   (TM36 cycle, covering TM48-TM42)
#                           ${daym1}06   (TM30 cycle, covering TM42-TM36)
#                           ${daym1}12   (TM24 cycle, covering TM36-TM30)
#                           ${daym1}18   (TM18 cycle, covering TM30-TM12)
#
#                      against the CPC 1/8 deg daily precip analysis
#                      covering the same time period, obtained from
#                           /dcom/us007003/$day/wgrbbul/rfc8.${daym1}12
#
#                      The NDAS hourly 'snow ratio' arrays are used to 
#                      determine whether a given grid point is snowing
#                      for the given hour.  During the 24h period 
#                      (${TM48}-${TM24}), if it snowed at a grid point
#                      in any hour, then this grid point is not used
#                      in the budget calculation.
#
#                      This script is called once a day, at the
#                      beginning of the 12Z cycle.
#
# Author:      Ying Lin     Org: NP22        Date: 2003-06-09
#

# Script history log:
# 2003-06-09  Y Lin
# 2003-12-11  Y Lin  Updated for 4-cycles-per-day configuration
# 2005-02-16  Y Lin  Updated to use lspa instead of bgrdsf file
# 2006-01-13  Y Lin  Since lspa / sratio are now in bgrdsf file, 
#                    use this instead of lspa
# 2008-06-11  Y Lin  Use the binary version of the CPC analysis from /dcom,
#      GRIB'd within this script, rather than the one pre-GRIB'd by us twice 
#      a day on a fixed schedule.  This will allow us to use more up-to-date
#      CPC analysis if CPC makes a re-run to correct for errors.  Also, check
#      for size of GRIB'd file, do not use if size < 95,000 bytes (most faulty
#      files fall under this category).
# 2009-04-22  Y Lin  B-grid version


set -x

cd $DATA

export XLFRTEOPTS="unit_vars=yes"

CYCTM18=`/nwprod/util/exec/ndate -18 $CYCLE`
PDYM18=`echo $CYCTM18 | cut -c 1-8`
HH18=`echo $CYCTM18 | cut -c 9-10`

CYCTM24=`/nwprod/util/exec/ndate -24 $CYCLE`
PDYM24=`echo $CYCTM24 | cut -c 1-8`
HH24=`echo $CYCTM24 | cut -c 9-10`

CYCTM30=`/nwprod/util/exec/ndate -30 $CYCLE`
PDYM30=`echo $CYCTM30 | cut -c 1-8`
HH30=`echo $CYCTM30 | cut -c 9-10`

CYCTM36=`/nwprod/util/exec/ndate -36 $CYCLE`
PDYM36=`echo $CYCTM36 | cut -c 1-8`
HH36=`echo $CYCTM36 | cut -c 9-10`

CYCTM48=`/nwprod/util/exec/ndate -48 $CYCLE`
PDYM48=`echo $CYCTM48 | cut -c 1-8`
HH48=`echo $CYCTM48 | cut -c 9-10`

daym1=`echo $CYCTM24 | cut -c 1-8`
daym2=`echo $CYCTM48 | cut -c 1-8`

export COM_NDAS=${COM_NDAS:-${COM_IN:-/com/nam/prod}}
DIRTM18=$COM_NDAS/ndas.$PDYM18
DIRTM24=$COM_NDAS/ndas.$PDYM24
DIRTM30=$COM_NDAS/ndas.$PDYM30
DIRTM36=$COM_NDAS/ndas.$PDYM36

# extract first 6 hours' of NDAS precip files from TM36, TM30, TM24 and TM18 
# cycles:

cp $DIRTM36/ndas.t${HH36}z.bgrdsf03.tm12 $CYCTM36.bgrdsf.tm12
cp $DIRTM36/ndas.t${HH36}z.bgrdsf03.tm09 $CYCTM36.bgrdsf.tm09

cp $DIRTM30/ndas.t${HH30}z.bgrdsf03.tm12 $CYCTM30.bgrdsf.tm12
cp $DIRTM30/ndas.t${HH30}z.bgrdsf03.tm09 $CYCTM30.bgrdsf.tm09

cp $DIRTM24/ndas.t${HH24}z.bgrdsf03.tm12 $CYCTM24.bgrdsf.tm12
cp $DIRTM24/ndas.t${HH24}z.bgrdsf03.tm09 $CYCTM24.bgrdsf.tm09

cp $DIRTM18/ndas.t${HH18}z.bgrdsf03.tm12 $CYCTM18.bgrdsf.tm12
cp $DIRTM18/ndas.t${HH18}z.bgrdsf03.tm09 $CYCTM18.bgrdsf.tm09

# Compute 24h sum (12Z-12Z) of adjusted hourly precip, also create
# daily snow map:

SUM24ADJ=YES
for file in $CYCTM36.bgrdsf.tm12 \
            $CYCTM36.bgrdsf.tm09 \
            $CYCTM30.bgrdsf.tm12 \
            $CYCTM30.bgrdsf.tm09 \
            $CYCTM24.bgrdsf.tm12 \
            $CYCTM24.bgrdsf.tm09 \
            $CYCTM18.bgrdsf.tm12 \
            $CYCTM18.bgrdsf.tm09

do
  if [ ! -e $file ]; then
    echo $file does not exist
    SUM24ADJ=NO
  fi
done

if [ $SUM24ADJ = YES ]; then
  export XLFUNIT_11="$CYCTM36.bgrdsf.tm12"
  export XLFUNIT_12="$CYCTM36.bgrdsf.tm09"
  export XLFUNIT_13="$CYCTM30.bgrdsf.tm12"
  export XLFUNIT_14="$CYCTM30.bgrdsf.tm09"
  export XLFUNIT_15="$CYCTM24.bgrdsf.tm12"
  export XLFUNIT_16="$CYCTM24.bgrdsf.tm09"
  export XLFUNIT_17="$CYCTM18.bgrdsf.tm12"
  export XLFUNIT_18="$CYCTM18.bgrdsf.tm09"
  export XLFUNIT_51="lspa.$CYCTM24.24h"
  export XLFUNIT_52="snowmask.$daym1"
  $EXECnam/nam_lspasno24h
  err=$?
  if [ $err -eq 0 ]; then
    cp lspa.$CYCTM24.24h $COMOUT/ndas.t${cyc}z.lspa.$CYCTM24.24h 
    cp snowmask.$daym1 $COMOUT/ndas.t${cyc}z.snowmask.$daym1
  else
    SUM24ADJ=NO
    echo 'Error making 24h sum of NDAS precip ending $CMCTM24'
  fi
fi

# 
# Get the CPC 1/8 deg daily analysis from /dcom:

cp /dcom/us007003/$daym1/wgrdbul/${daym1}.ll .
err1=$?

if [ -s $daym1.ll ]; then
  datem2=`/nwprod/util/exec/ndate -24 ${daym1}12`
  echo $datem2 > startdate
  export XLFUNIT_11="startdate"
  export XLFUNIT_12="${daym1}.ll"
  export XLFUNIT_51="cpcanl.${daym1}.grb"
  export XLFUNIT_52="dummy.ascii"
  /nwprod/exec/nam_cpc2grbrfc8
else
  echo 'Cannot find CPC analysis on /dcom.  Exit.'
  exit
fi

/nwprod/ush/wwgrib.pl cpcanl.${daym1}.grb
err=$?

if [ $err -ne 0 ]; then
  echo 'cpcanl.${daym1}.grb is not a valid GRIB file.  Exit.'
  exit
fi

let filesize=`ls -l cpcanl.${daym1}.grb |awk '{print $5}'`
if [ $filesize -lt 95000 ]; then
  echo 'cpcanl.${daym1}.grb is too small: likely to be faulty.  Exit.'
  exit
fi

# When grid #99 (expanded NAM domain) added to w3lib and copygb is
# recompiled uncomment out the next line and remove the next copygb
# execution

# Map to expanded 12-km NAM B-grid

# These will be used when George's new ip/w3 libs are put into parallel
grid="255 205 954 835 -7491 -144134 136 54000 -106000 126 108 64 44539 14802"
COPYGB=${COPYGB:-$utilexec/copygb}
$COPYGB -g "${grid}" -i3 -x cpcanl.${daym1}.grb cpcanl.${daym1}.bgrid

cp cpcanl.${daym1}.bgrid $COMOUT/ndas.t${cyc}z.cpcanl.${daym1}.bgrid

$USHnam/wwgrib.pl cpcanl.${daym1}.bgrid
err=$?
if [ $err -ne 0 ]; then
  echo 'Error making daily analysis on G99'
  exit
fi

# copy over old water budget history file.  
# It's safer to copy from previous day's 12Z NDAS directory.  During 
# the 32km NAMY tests, the 2003091612 run apparently got re-started 
# 3-times (production pre-empt'd development), so the exndas_h2obudget.sh 
# job was run three times.  There was no pcpbudget_history file from the 
# previous day, but because of this triple-run, the pcpbudget_history ended 
# up to have triple the amount of the day's budget (computed for the 24h
# ending 2003091612).
#
# Use the pcpbudget_history in nam*pll.hold as a backup, otherwise when
# one cycle is missing we'd have to start from scratch.  So we'll use
# ndasnam.$CYCTM24 as the primary location and nam.hold as the
# secondary location when looking for pcpbudget_history.
# 

cp $DIRTM24/ndas.t${HH24}z.pcpbudget_history pcpbudget_history.old
err1=$?

if [ $err1 -eq 0 ]; then
  HISTORY=history
else
  cp $gespath/ndas.hold/pcpbudget_history pcpbudget_history.old
  err2=$?
  if [ $err2 -eq 0 ]; then
    HISTORY=history
  else
    HISTORY=nohistory
    echo 'Old pcpbudget_history file not found.  Start accounting from scratch'
  fi
fi

export XLFUNIT_11="cpcanl.${daym1}.bgrid"
export XLFUNIT_12="lspa.${daym1}12.24h"
export XLFUNIT_13="snowmask.$daym1"
export XLFUNIT_14="pcpbudget_history.old"
export XLFUNIT_51="pcpbudget.$daym1"
export XLFUNIT_52="pcpbudget_history"
export XLFUNIT_53="avgbudsum.$daym1"
$EXECnam/nam_pcpbudget << ioEOF
$daym1
$HISTORY
ioEOF

err=$?

if [ $err -ne 0 ]; then
  echo $daym1 Error running pcpbudget.x
  exit
else
  cp lspa.${daym1}12.24h $COMOUT/ndas.t${cyc}z.lspa.${daym1}12.24h
  cp pcpbudget.$daym1 $COMOUT/ndas.t${cyc}z.pcpbudget.$daym1
  cp pcpbudget_history $COMOUT/ndas.t${cyc}z.pcpbudget_history
  cp avgbudsum.$daym1 $COMOUT/ndas.t${cyc}z.avgbudsum.$daym1
  mv $gespath/ndas.hold/pcpbudget_history $gespath/ndas.hold/pcpbudget_history.old
  cp pcpbudget_history $gespath/ndas.hold/.
fi

echo EXITING $0 with return code $err
exit $err

