#! /bin/ksh
################################################################
# hwrf_post_process.sh
####################
# This script runs the HWRF postprocessing for a single output time
# for two or three HWRF domains.  This script must be run in its
# own directory, and will fill it with temporary files.  This is part
# of a rewrite of Vijay Tallapragada's original hwrf_post.sh script.
# This script also requires hwrf_post_master.sh and hwrf_post_deliver.sh.
#
# Written March 2011 by Sam Trahan
################################################################

set -x

function die {
    sh ${utilscript}/setup.sh
    err=911
    echo "$*"
    err_exit "$*"
    exit 2
}

function usage {
    cat<<EOF
Format: $0 [options] STORMNAME STORMID YYYYMMDDHH /path/to/fort_14 \\
   CENLAT CENLON \\
   /path/to/wrfout_d01_YYYY-MM-DD_hh:mm:ss \\
     [ /path/to/wrfout_d02_YYYY-MM-DD_hh:mm:ss \\
         [ /path/to/wrfout_d03_YYYY-MM-DD_hh:mm:ss ] ]

where domains 2 and 3 are optional.  This will post-process the given
files using the specified post control file (fort_14) and create
various GRIB files in the current working directory.  If "-n" is given,
then the script assumes the numerous synthetic satellite fix files are
unneeded, and does not copy them.

This script expects the following environment variables will be set:

\$PARAFLAG -- YES, unless you are NCO, running operationally
\$FIXhwrf -- location of HWRF fix/ directory
\$EXEChwrf -- location of HWRF exec/ directory
\$utilexec -- location of utility programs wgrib, ndate and copygb
\$NWPROD -- used if \$utilexec is unset.  Location of /nwprod or nwjet/
\$IO_FORM -- type of wrfout file: 1=binary, 2=netcdf.  Default: 1 (binary)
\$DIAG, \$IDIAG -- set to 1 to get additional high-resolution output
\$DATA -- directory that contains simulation.sig

\$SIMULATION_SIG -- Only for PARAFLAG=YES (non-NCO).  The files will
only be processed if the file \$DATA/simulation.sig contains the value
in \$SIMULATION_SIG.  To disable the signature, set it to "none".  If
\$SIMULATION_SIG is unset, it will be set to the value of
\$DATA/simulation.sig.

When running as NCO in operations, all variables are optional.

The following dash options can be sent:

    -n -- no synthetic satellite input files will be created (speeds up script)

    -2 -- only use the first two domains when producing the combine_grbf file,
        even if more than two domains are available

    -t 2011-09-14_18:00:00 -- force a specific time stamp, regardless of the
          actual filename
EOF
    die SCRIPT IS ABORTING DUE TO INCORRECT ARGUMENTS.
}

# Parse the dash options (-n, -t)

maybesat=YES
forcedate=""
go=yes
combine2dom=NO
while [[ "$go" == yes ]] ; do
    case "$1" in
        -n) maybesat=NO ; shift 1 ;;
        -t) forcedate="$2" ; shift 2 ;;
        -2) combine2dom=YES ; shift 1 ;;
        --) shift 1 ; go=no ;;
        *) go=no
    esac
done

if [[ "$#" -lt 7 || "$#" -gt 9 ]] ; then
    usage
fi

STORM="$1"
STORMID="$2"
ymdh="$3"
fort_14="$4"
CENLA="$5"
CENLO="$6"
d01="$7"
d02="$8"
d03="$9"

if [[ "$d02" == none || -z "$d02" ]] ; then
    maxdom=1
    last="$d01"
elif [[ "$d03" == none || -z "$d03" ]] ; then
    maxdom=2
    last="$d02"
else
    maxdom=3
    last="$d03"
fi

wrfdir=$( dirname "$last" ) # directory where WRF was run
if [[ $( echo "$wrfdir" | cut -c 1-1 ) != / ]] ; then
    # $wrfdir is a relative path, so prepend current working directory
    wrfdir=$( pwd )/$wrfdir
fi
if [[ -z "$wrfdir" || ! -d "$wrfdir" ]] ; then
    die "Cannot get directory of wrfout file $last"
fi

########################################################################
# Determine file types and executable locations:

if [[ "$PARAFLAG" != YES ]] ; then
    FIXhwrf="${FIXhwrf:-${NWPROD}/hwrf.${HWRF_VERSION}/fix/}"
    EXEChwrf="${EXEChwrf:-${NWPROD}/hwrf.${HWRF_VERSION}/exec/}"
fi
utilexec=${utilexec:-${NWPROD}/util/exec}
ndate=${utilexec}/ndate
grb2ctl=${USHhwrf}/hwrf_grib2ctl.pl
wgrib=${utilexec}/wgrib
cgb=${utilexec}/copygb
grbmap=/usrx/local/grads/bin/gribmap  # path hard-coded in operational HWRF

if [[ "$PARAFLAG" == YES ]] ; then
    # override NCO's hard-coded path
    grbmap=$( /usr/bin/which gribmap )
    if [[ -z "$grbmap" || ! -x "$grbmap" ]] ; then
        echo WARNING: gribmap is not in your path.  I will check some default locations.
        grbmap=/bin/false

        # Vapor: /usrx/local/grads/bin/gribmap
        # CCS:   /usrx/local/grads/bin/gribmap
        # Jet:   /opt/grads/2.0.a2/bin/gribmap
      
        for find_grbmap in  /usrx/local/grads/bin/gribmap /opt/grads/2.0.a2/bin/gribmap MISSING ; do
            if [[ -x "$find_grbmap" ]] ; then 
                break
            fi
        done
        
        if [[ "$find_grbmap" == MISSING ]] ; then
            echo "WARNING: I cannot find gribmap, so the grads input files *.ctl and *.idx will not be produced."
            echo "         That will not affect the operational system, but you will have to produce the "
            echo "         grads input files yourself if you want them."
            grbmap=gribmap # provide no path, and hope for the best
        else
            grbmap="$find_grbmap"
        fi
    fi
fi

namelist=''

if [[ "$PARAFLAG" == YES ]] ; then
    if [[ "$IO_FORM" == 2 ]] ; then
        wrf_out_type=netcdf
        post_exec=$EXEChwrf/hwrf_post
    else
        wrf_out_type=binarympiio
        post_exec=$EXEChwrf/hwrf_post
    fi
else
    wrf_out_type=binarympiio
    post_exec=$EXEChwrf/hwrf_post
fi

########################################################################
# Determine dates and file basenames

# $dXX and $last:  /path/to/wrfout_d02_2010-09-21_12:00:00
# $bXX and $blast: wrfout_d02_2010-09-21_12:00:00
# $last & $blast: last (highest numbered) domain

# We use the last domain to get the times since the last domain
# has the smallest timestep and will be output closest to the
# requested output time.

b01=$( basename "$d01" )
b02=$( basename "$d02" )
b03=$( basename "$d03" )
blast=$( basename "$last" )

yyyy=$( echo $blast | cut -c12-15 )
mm=$( echo $blast | cut -c17-18 )
dd=$( echo $blast | cut -c20-21 )
hh=$( echo $blast | cut -c23-24 )

gridfile=grid_$STORM.$ymdh       # low-res 0.25 degree grid
hr_gridfile=hr_grid_$STORM.$ymdh # high-res 0.1 degree grid

    # Grid is centered at hour 0 outer domain center:
STORMLAT="$CENLA"
STORMLON="$CENLO"
if [[ -z "$STORMLAT" || -z "$STORMLON" ]] ; then
    die "STORMLAT=\"$STORMLAT\" and STORMLON=\"$STORMLON\" -- must not be empty"    
fi
echo $STORMLAT  $STORMLON
STORMLON=`echo $STORMLON + 360 | bc` # ensure positive longitudes

# Use 90 latitude degrees by 110 longitude degrees around center:
NORTHB=`echo "$STORMLAT" | awk '{print ($1+45)*1000}'`
SOUTHB=`echo "$STORMLAT" | awk '{print ($1-45)*1000}'`
WESTB=` echo "$STORMLON" | awk '{print ($1+55)*1000}'`
EASTB=` echo "$STORMLON" | awk '{print ($1-55)*1000}'`
echo $NORTHB $SOUTHB $EASTB $WESTB

# Put the post domains in temporary files first since multiple jobs
# may be making the post domain file at the same time, and we don't
# want partial writes
temp_gridfile="$gridfile.$$.$RANDOM.$RANDOM.$RANDOM.$( hostname )"
temp_hr_gridfile="$hr_gridfile.$$.$RANDOM.$RANDOM.$RANDOM.$( hostname )"
echo 255 0 441 361 ${NORTHB} ${EASTB} 136 ${SOUTHB} ${WESTB} 250 250 0 > "$temp_gridfile"
echo 255 0 1101 901 ${NORTHB} ${EASTB} 136 ${SOUTHB} ${WESTB} 100 100 0 > "$temp_hr_gridfile"

# Move the temporary grid files to the new grid files
/bin/mv -f "$temp_gridfile" "$gridfile"
/bin/mv -f "$temp_hr_gridfile" "$hr_gridfile"

if [[ ! -s "$gridfile" ]] ; then
    die "Low-res grid file $gridfile is empty or non-existant"
fi
if [[ ! -s "$hr_gridfile" ]] ; then
    die "High-res grid file $gridfile is empty or non-existant"
fi
grid=$( cat "$gridfile" )
hr_grid=$( cat "$hr_gridfile" )
echo "POST LOW-RES DOMAIN:  $( cat $gridfile )"
echo "POST HIGH_RES DOMAIN: $( cat $hr_gridfile )"

########################################################################
# Link to the various fixed files needed by the post-processor

cp $FIXhwrf/hwrf_eta_micro_lookup.dat ./eta_micro_lookup.dat 

if [[ "$maybesat" == YES ]] ; then
    /bin/cp -pf $FIXhwrf/hwrf_CRTM_imgr_g11.SpcCoeff.bin_goestb ./imgr_g11.SpcCoeff.bin
    /bin/cp -pf $FIXhwrf/hwrf_CRTM_imgr_g11.TauCoeff.bin_goestb ./imgr_g11.TauCoeff.bin
    /bin/cp -pf $FIXhwrf/hwrf_CRTM_imgr_g12.SpcCoeff.bin_goestb ./imgr_g12.SpcCoeff.bin
    /bin/cp -pf $FIXhwrf/hwrf_CRTM_imgr_g12.TauCoeff.bin_goestb ./imgr_g12.TauCoeff.bin
    /bin/cp -pf $FIXhwrf/hwrf_CRTM_EmisCoeff.bin_goestb ./EmisCoeff.bin
    /bin/cp -pf $FIXhwrf/hwrf_CRTM_AerosolCoeff.bin_goestb ./AerosolCoeff.bin
    /bin/cp -pf $FIXhwrf/hwrf_CRTM_CloudCoeff.bin_goestb ./CloudCoeff.bin 

    /bin/cp -pf $FIXhwrf/HWRFSpcCoeff/amsre_aqua.SpcCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFTauCoeff/amsre_aqua.TauCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFSpcCoeff/tmi_trmm.SpcCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFTauCoeff/tmi_trmm.TauCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFSpcCoeff/ssmi_f15.SpcCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFTauCoeff/ssmi_f15.TauCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFSpcCoeff/ssmis_f17.SpcCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFTauCoeff/ssmis_f17.TauCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFSpcCoeff/ssmis_f20.SpcCoeff.bin   ./
    /bin/cp -pf $FIXhwrf/HWRFTauCoeff/ssmis_f20.TauCoeff.bin   ./
fi

########################################################################
# Loop over all domains, running the post and copygb

for domain in $( seq 1 $maxdom ) ; do
    # Decide filenames
    if [[ "$PARAFLAG" == YES ]] ; then
        $USHhwrf/hwrf_port_checksig.sh
    fi
    case "$domain" in
        1) infile="$d01" ; outpre=HWRFPRS_PARENT.Grb ;;
        2) infile="$d02" ; outpre=HWRFPRS_NEST.Grb ;;
        3) infile="$d03" ; outpre=HWRFPRS_DOM3.Grb ;;
        *) die "Internal error: domain=$domain is not 1, 2 or 3" ;;
    esac

    # Clean up the directory
    rm -f INFILE itag WRFPRS.GrbF* fort.14 vpost_log
    if [[ "$PARAFLAG" == YES ]] ; then
        $USHhwrf/hwrf_port_cachesync.sh
    fi
    ln -s "$infile" INFILE
    if [[ -z "$forcedate" ]] ; then
        date_stamp=$( basename $infile | cut -c12-30 )
    else
        date_stamp="$forcedate"
    fi
    cat<<EOF > itag
INFILE
$wrf_out_type
$date_stamp
NMM
EOF
    sync
    rc=1 
    sh ${utilscript}/setup.sh

    # Link fort.14 to the correct post control file
    cp -pf "$fort_14" fort.14

    fail=yes
    maxtries=5
    for tries in $( seq 1 $maxtries ) ; do
        if [[ "$PARAFLAG" == YES ]] ; then
            $USHhwrf/hwrf_port_checksig.sh
        fi

        # Run the post.
        $USHhwrf/hwrf_run.sh $post_exec < itag > vpost_log 2>&1

        # Figure out if the post succeeded:
        rc=$?
        if [[ "$rc" != 0 ]] ; then
            echo WARNING: GOT RETURN VALUE $rc FROM $post_exec.  CHECKING FOR A SUCCESS MESSAGE IN LOG FILE.
            if ( grep 'ALL GRIDS PROCESSED'                                vpost_log > /dev/null ) ; then 
                # The UPP will often return non-zero exit status after succeeding, so 
                # this is a workaround:
                rc=0
                rm -rf core*
            else
                export err=$rc
                if [ $err -ne 0 ]; then
                    echo "$post_exec failed for wrfout_d01 hour $this_hour -- retry after 3 minute sleep"
                    sleep 180
                    echo "Slept 3 minutes.  Now retrying."
                    continue
                fi
            fi
        fi
        if [[ "$PARAFLAG" == YES ]] ; then
            $USHhwrf/hwrf_port_checksig.sh
        fi
        post_out_file=$( echo $( ls -tr1 WRFPRS.GrbF* | tail -1 ) )
        if [[ ! -s "$post_out_file" ]] ; then
            echo "$post_exec output file $post_out_file is empty or no post file was produced -- retry after 3 minute sleep"
            sleep 180
            echo "Slept 3 minutes.  Now retrying."
            continue
        fi

        # If we get here, the post succeeded, so we must exit the loop
        fail=no
        break
    done

    if [[ "$fail" == yes ]] ; then
        die "POST FAILED $maxtries TIMES ON $infile -- ABORTING."
    fi

    hour=$( ls -1 WRFPRS.GrbF* | perl -ne '
           chomp;
           /^WRFPRS.GrbF0*(0|[1-9]\d*)$/
              or die "CANNOT PARSE \"$_\"";
           print "$1\n";
           exit 0;
    ' )
    if [[ "$PARAFLAG" == YES ]] ; then
        $USHhwrf/hwrf_port_checksig.sh
    fi
    hour00=$( printf %02d "$hour" ) # 0 becomes 00 and 6 becomes 06
    if [[ -z "$hour00" ]] ; then
        die "Cannot parse hour from filenames WRFPRS.GrbF* : " $( ls -1 WRFPRS.GrbF* )
    fi

    /bin/mv -f WRFPRS.GrbF* "$outpre"F$( printf %02d $hour )
    
    if [[ "$PARAFLAG" == YES ]] ; then
        $USHhwrf/hwrf_port_checksig.sh
    fi
    # Interpolate to lat-lon grids and subset variables
    if [[ "$domain" == 1 ]] ; then
        wrfprs_file=HWRFPRS_PARENT.GrbF$hour00
        final_grib=HWRF_PARENT.GrbF$hour00
        select_grib=hwrf_parent.grbf$hour00
        if [[ $DIAG = 1 ]]; then
            if [[ $IDIAG = 1 ]]; then
                ####### High-res grib files for parent domain ######
                if [[ "$PARAFLAG" == YES ]] ; then
                    $USHhwrf/hwrf_port_checksig.sh
                fi
                final_grib=HWRF_PARENT.Grb10thF$hour00
                $cgb $namelist -g"$hr_grid" -x $wrfprs_file $final_grib
                $grb2ctl -verf $final_grib > $final_grib.ctl
                $grbmap -i $final_grib.ctl
            else
                ####### Low-res grib files for parent domain #######
                if [[ "$PARAFLAG" == YES ]] ; then
                    $USHhwrf/hwrf_port_checksig.sh
                fi
                final_grib=HWRF_PARENT.GrbF$hour00
                $cgb $namelist -g"$grid" -x $wrfprs_file $final_grib
                $grb2ctl -verf $final_grib > $final_grib.ctl
                $grbmap -i $final_grib.ctl
            fi
            if [[ $hour00 == 00 && "$DIAG0" == 1 ]]; then
                ####### High-res for all variables at time 0 #######
                if [[ "$PARAFLAG" == YES ]] ; then
                    $USHhwrf/hwrf_port_checksig.sh
                fi
                final_grib=HWRF_PARENT.Grb10thF$hour00
                $cgb $namelist -g"$hr_grid" -x $wrfprs_file $final_grib
                $grb2ctl -verf $final_grib > $final_grib.ctl
                $grbmap -i $final_grib.ctl
            fi
            
        fi

        ################################################################
        # Now produce High Resolution (0.1 deg.) grib files for selected
        # variables for the PARENT domain
        ################################################################
        $wgrib -s $final_grib > $final_grib.wgrib.index
        if [ $IDIAG = 1 ]; then
            if [[ "$PARAFLAG" == YES ]] ; then
                $USHhwrf/hwrf_port_checksig.sh
            fi
            cat $final_grib.wgrib.index|egrep -i "(UGRD:700|UGRD:850|UGRD:500)"|grep " mb:"|$wgrib -i -grib -append $final_grib -o $select_grib 
            cat $final_grib.wgrib.index|egrep -i "(VGRD:700|VGRD:850|VGRD:500)"|grep " mb:"|$wgrib -i -grib -append $final_grib -o $select_grib 
            cat $final_grib.wgrib.index|egrep -i "(ABSV:700|ABSV:850)"|grep " mb:"|$wgrib -i -grib -append $final_grib -o $select_grib 
            cat $final_grib.wgrib.index|egrep -i "(HGT:700|HGT:850)"|grep " mb:"|$wgrib -i -grib -append $final_grib -o $select_grib 
            cat $final_grib.wgrib.index|egrep -i "GRD:10 m above"|$wgrib -i -grib -append $final_grib -o $select_grib 
            cat $final_grib.wgrib.index|egrep -i "PRMSL|VAR|:var|SBT|BRT|AMSRE" | $wgrib -i -grib -append $final_grib -o $select_grib 
            final_grib=$STORM$STORMID.$ymdh.parent_grb10thf$hour00
            /bin/mv $select_grib $final_grib
        ################################################################
        else
            if [[ "$PARAFLAG" == YES ]] ; then
                $USHhwrf/hwrf_port_checksig.sh
            fi
            $wgrib -s $wrfprs_file > $wrfprs_file.wgrib.index
            cat $wrfprs_file.wgrib.index|egrep -i "(UGRD:700|UGRD:850|UGRD:500)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
            cat $wrfprs_file.wgrib.index|egrep -i "(VGRD:700|VGRD:850|VGRD:500)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
            cat $wrfprs_file.wgrib.index|egrep -i "(ABSV:700|ABSV:850)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
            cat $wrfprs_file.wgrib.index|egrep -i "(HGT:700|HGT:850)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
            cat $wrfprs_file.wgrib.index|egrep -i "GRD:10 m above"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
            cat $wrfprs_file.wgrib.index|egrep -i "PRMSL|VAR|:var|SBT|BRT|AMSRE"  | $wgrib -i -grib -append $wrfprs_file -o $select_grib 
            
            final_grib=$STORM$STORMID.$ymdh.parent_grbf$hour00
            $cgb $namelist -g"$hr_grid" -x $select_grib  $final_grib
        fi
    # end domain 1 copygb processing and wgrib subsetting
    elif [[ "$domain" -gt 1 ]] ; then
        if [[ "$domain" == 2 ]] ; then
            NEST=NEST
            nest=nest
        else
            NEST=DOM3
            nest=dom3
        fi
        wrfprs_file=HWRFPRS_$NEST.GrbF$hour00
        final_grib=HWRF_$NEST.GrbF$hour00
        select_grib=hwrf_$nest.grbf$hour00
        if [[ "$PARAFLAG" == YES ]] ; then
            $USHhwrf/hwrf_port_checksig.sh
        fi
        if [[ $DIAG = 1 ]]; then
            ################################################################
            # Produce high-resolution (0.1 deg) grib files for all variables
            # for the NEST domain
            ################################################################
            clat=`$wgrib -V $wrfprs_file |head -6 |tail -1 |awk '{print $8}' |cut -c1-8`
            clon=`$wgrib -V $wrfprs_file |head -6 |tail -1 |awk '{print $6}'`
            if [[ "$domain" == 2 ]] ; then
                nlat=`echo "$clat" | awk '{print ($1+6)*1000}'`
                slat=`echo "$clat" | awk '{print ($1-6)*1000}'`
                wlon=`echo "$clon" | awk '{print ($1+7)*1000}'`
                elon=`echo "$clon" | awk '{print ($1-7)*1000}'`
                echo 255 0 141 121 ${nlat} ${elon} 136 ${slat} ${wlon} 100 100 0 > ${nest}_grid
                d2grid=$( cat ${nest}_grid )
            else
                nlat=`echo "$clat" | awk '{print int(($1+3)*1000)}'`
                slat=`echo "$clat" | awk '{print int(($1-3)*1000)}'`
                wlon=`echo "$clon" | awk '{print int(($1+3.75)*1000)}'`
                elon=`echo "$clon" | awk '{print int(($1-3.75)*1000)}'`
                echo 255 0 251 201 ${nlat} ${elon} 136 ${slat} ${wlon} 30 30 0 > ${nest}_grid
                d3grid=$( cat ${nest}_grid )
            fi
            n_grid=`cat ${nest}_grid`
            echo before ${nest} cgb 1:
            echo wrfprs_file
            ls -l "$wrfprs_file"
            $cgb $namelist -g"$n_grid" -x $wrfprs_file $final_grib
            if [[ "$PARAFLAG" == YES ]] ; then
                $USHhwrf/hwrf_port_checksig.sh
            fi
            echo before $nest grb2ctl 1:
            echo final_grib
            ls -l "$final_grib"
            $grb2ctl -verf $final_grib > $final_grib.ctl
            if [[ "$PARAFLAG" == YES ]] ; then
                $USHhwrf/hwrf_port_checksig.sh
            fi
            echo before $nest grbmap 1:
            echo final_grib
            ls -l "$final_grib"
            $grbmap -i $final_grib.ctl
            
            if [[ $hour00 == 00 && "$DIAG0" == 1 ]]; then
                final_grib=HWRF_$NEST.Grb10thF$hour00
                echo before $nest cgb 2:
                echo wrfprs_file
                if [[ "$PARAFLAG" == YES ]] ; then
                    $USHhwrf/hwrf_port_checksig.sh
                fi
                ls -l "$wrfprs_file"
                $cgb $namelist -g"$hr_grid" -x $wrfprs_file $final_grib
                echo before $nest grb2ctl 2:
                echo final_grib
                if [[ "$PARAFLAG" == YES ]] ; then
                    $USHhwrf/hwrf_port_checksig.sh
                fi
                ls -l "$final_grib"
                $grb2ctl -verf $final_grib > $final_grib.ctl
                echo before $nest grbmap 2:
                echo final_grib
                if [[ "$PARAFLAG" == YES ]] ; then
                    $USHhwrf/hwrf_port_checksig.sh
                fi
                ls -l "$final_grib"
                $grbmap -i $final_grib.ctl
            fi
        fi
        ################################################################
        # Now produce High Resolution (0.1 deg.) grib files for selected
        # variables for the NEST domain
        ################################################################
        $wgrib -s $wrfprs_file > $wrfprs_file.wgrib.index
        cat $wrfprs_file.wgrib.index|egrep -i "(UGRD:700|UGRD:850|UGRD:500)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
        cat $wrfprs_file.wgrib.index|egrep -i "(VGRD:700|VGRD:850|VGRD:500)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
        cat $wrfprs_file.wgrib.index|egrep -i "(ABSV:700|ABSV:850)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
        cat $wrfprs_file.wgrib.index|egrep -i "(HGT:700|HGT:850)"|grep " mb:"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
        cat $wrfprs_file.wgrib.index|egrep -i "GRD:10 m above"|$wgrib -i -grib -append $wrfprs_file -o $select_grib 
        cat $wrfprs_file.wgrib.index|egrep -i "PRMSL|:var|VAR|SBT|BRT|AMSRE" |$wgrib -i -grib -append $wrfprs_file -o $select_grib 
        if [[ "$PARAFLAG" == YES ]] ; then
            $USHhwrf/hwrf_port_checksig.sh
        fi

        final_grib=$STORM$STORMID.$ymdh.${nest}_grbf$hour00
        echo before $nest cgb 3:
        echo wrfprs_file
        ls -l "$select_grib"
        $cgb $namelist -g"$hr_grid" -x $select_grib  $final_grib
        if [[ "$PARAFLAG" == YES ]] ; then
            $USHhwrf/hwrf_port_checksig.sh
        fi
    fi

    if [[ "$maxdom" -ge 3 && "$domain" -gt 1 ]] ; then
        echo make move file for domain $domain
        d2file=HWRF_MOV2.GrbF$hour00
        d3file=HWRF_MOV3.GrbF$hour00
        d23file=HWRF_MOVE.GrbF$hour00


        if [[ "$domain" == 2 ]] ; then
            wrfprs_file=HWRFPRS_NEST.GrbF$hour00
            out_file=$d2file

            clat=`$wgrib -V $wrfprs_file |head -6 |tail -1 |awk '{print $8}' |cut -c1-8`
            clon=`$wgrib -V $wrfprs_file |head -6 |tail -1 |awk '{print $6}'`
            nlat=`echo "$clat" | awk '{print int(($1+6)*1000)}'`
            slat=`echo "$clat" | awk '{print int(($1-6)*1000)}'`
            wlon=`echo "$clon" | awk '{print int(($1+7.5)*1000)}'`
            elon=`echo "$clon" | awk '{print int(($1-7.5)*1000)}'`
            echo 255 0 501 401 ${nlat} ${elon} 136 ${slat} ${wlon} 30 30 0 > d23_grid_f$hour00
            d23grid=$( cat d23_grid_f$hour00 )
        else
            wrfprs_file=HWRFPRS_DOM3.GrbF$hour00
            out_file=$d3file
            d23grid=$( cat d23_grid_f$hour00 )
        fi

        moving_grib=$STORM$STORMID.$ymdh.moving_grbf$hour00

        echo wrfprs_file:
        ls -l $wrfprs_file
        $cgb $namelist -g"$d23grid" -x $wrfprs_file $out_file
        if [[ ! -s "$out_file" ]] ; then
            die "Unable to make $out_file"
        fi
        $grb2ctl -verf $out_file > $out_file.ctl
        $grbmap -i $out_file.ctl

        if [[ "$domain" == 3 ]] ; then
            # Merge the domain 2 and domain 2/3 file into one file
            echo d2file:
            ls -l $d2file
            echo d3file:
            ls -l $d3file
            $cgb $namelist -g"$d23grid" -xM $d2file $d3file $d23file
            if [[ ! -s "$d23file" ]] ; then
                die "Unable to make $d23file"
            fi
            $grb2ctl -verf $d23file > $d23file.ctl
            $grbmap -i $d23file.ctl
        fi
    fi

    if [[ "$domain" == "$maxdom" && "$maxdom" -gt 1 ]] ; then
        ################################################################
        # Produce High Resolution (0.1 deg.) grib files for all
        # variables for the COMBINED domain at initial time
        ################################################################
        if [[ $hour00 == 00 && "$DIAG0" == 1 ]]; then
            if [[ "$PARAFLAG" == YES ]] ; then
                $USHhwrf/hwrf_port_checksig.sh
            fi
            echo before nest cgb merge 1:
            if [[ "$maxdom" -ge 3 ]] ; then
                ls -l "HWRF_NEST.Grb10thF$hour00"
                $cgb -g"$hr_grid" -xM HWRF_PARENT.Grb10thF$hour00 HWRF_NEST.Grb10thF$hour00 \
                    $STORM$STORMID.$ymdh.combine12_grb10thf$hour00
                ls -l "HWRF_DOM3.Grb10thF$hour00"
                $cgb -g"$hr_grid" -xM HWRF_NEST.Grb10thF$hour00 HWRF_DOM3.Grb10thF$hour00 \
                    $STORM$STORMID.$ymdh.combine23_grb10thf$hour00
                ls -l "$STORM$STORMID.$ymdh.combine23_grb10thf$hour00"
                $cgb -g"$hr_grid" -xM HWRF_PARENT.Grb10thF$hour00 \
                    $STORM$STORMID.$ymdh.combine23_grb10thf$hour00 \
                 $STORM$STORMID.$ymdh.combine_grb10thf$hour00
            else
                $cgb -g"$hr_grid" -xM HWRF_PARENT.Grb10thF$hour00 HWRF_NEST.Grb10thF$hour00 \
                    $STORM$STORMID.$ymdh.combine_grb10thf$hour00
            fi
            echo after, merged grib:
            ls -l "$STORM$STORMID.$ymdh.combine_grb10thf$hour00"
        fi
        ################################################################
        # Produce High Resolution (0.1 deg.) grib files for selected
        # variables for the COMBINED domain
        ################################################################
        rm -f date_file
        echo ${nrec} > date_file
        echo before nest cgb merge 2:
        ls -l $STORM$STORMID.$ymdh.parent_grbf$hour00
        ls -l $STORM$STORMID.$ymdh.nest_grbf$hour00
        if [[ "$maxdom" -ge 3 && "$combine2dom" != YES ]] ; then
         $cgb -g"$hr_grid" -xM$STORM$STORMID.$ymdh.parent_grbf$hour00 $STORM$STORMID.$ymdh.nest_grbf$hour00 \
                $STORM$STORMID.$ymdh.combine12_grbf$hour00
            ls -l $STORM$STORMID.$ymdh.dom3_grbf$hour00
            $cgb -g"$hr_grid" -xM$STORM$STORMID.$ymdh.nest_grbf$hour00 $STORM$STORMID.$ymdh.dom3_grbf$hour00 \
                $STORM$STORMID.$ymdh.combine23_grbf$hour00
            ls -l $STORM$STORMID.$ymdh.combine23_grbf$hour00
            $cgb -g"$hr_grid" -xM$STORM$STORMID.$ymdh.parent_grbf$hour00 $STORM$STORMID.$ymdh.combine23_grbf$hour00 \
             $STORM$STORMID.$ymdh.combine_grbf$hour00
        else
            $cgb -g"$hr_grid" -xM$STORM$STORMID.$ymdh.parent_grbf$hour00 $STORM$STORMID.$ymdh.nest_grbf$hour00 \
                $STORM$STORMID.$ymdh.combine_grbf$hour00
        fi
        echo after, merged file:
        ls -l $STORM$STORMID.$ymdh.combine_grbf$hour00
        if [[ "$PARAFLAG" == YES ]] ; then
            $USHhwrf/hwrf_port_checksig.sh
        fi
    fi
done

echo 'SUCCESSFUL COMPLETION OF POST PROCESSING SCRIPT hwrf_post_one.sh'

exit 0
