#!/bin/ksh
##########################################################
# hwrf_merge.sh
#########################
# This script produces the wrfanl_d01 and wrfanl_d02 files 
# (similar to those obtained from hwrf_nmm_real.sh).
# Usage: 
# sh hwrf_merge.sh storm YEAR MONTH DATE CYCLE storm_id 
#
# Executables
# hwrf_bin_io     copied as ./hwrf_bin_io.exe
# hwrf_inter_2to1 copied as ./hwrf_inter_2to1.x
# hwrf_inter_2to6 copied as ./hwrf_inter_2to6.x
# hwrf_guess      copied as ./hwrf_guess.x
#
# April 2007 Written by Qingfu Liu
# April 2007 Revised for operations Vijay Tallapragada
# April 2008 Revised to include new Analysis procedure 
#            Qingfu Liu and Vijay Tallapragada
# June 2009 Modified for HWRF 2009 implementation by Vijay Tallapragada
##########################################################
set -x
if [ $INIT == NO -a $GSI == NO ]; then
echo 'Initialization not requested.  INIT = $INIT GSI = $GSI This script need not be run'
sh ${utilscript}/setup.sh
err=911
err_exit 'Initialization not requested. This script need not be run'
fi
########## GET THE INPUT VARIABLES #######################
if [ $# -eq 6 ]
then
   export storm=${1}
   export YEAR=${2}
   export MONTH=${3}
   export DATE=${4}
   export CYCLE=${5}
   export storm_id=${6}

   echo 'storm    = ' ${storm}
   echo 'YEAR     = ' ${YEAR}
   echo 'MONTH    = ' ${MONTH}
   echo 'DATE     = ' ${DATE}
   echo 'CYCLE    = ' ${CYCLE}
   echo 'storm_id = ' ${storm_id}
else
   echo 'Usage:'
   echo 'sh hwrf_merge.sh storm YEAR MONTH DATE CYCLE storm_id'
   echo 'NEED SIX ARGUMENTS'
   echo 'SCRIPT WILL EXIT'
sh ${utilscript}/setup.sh
err=911
err_exit 'NEED SIX ARGUMENTS'
fi
################################################################

export cdate=$YEAR$MONTH$DATE$CYCLE
echo 'cdate = ' ${cdate}

# Set utilities pathways 
ndate=${utilexec}/ndate

gdate=`$ndate -06 $cdate`
yyyy=` echo $cdate | cut -c 1-4 `
im=`   echo $cdate | cut -c 5-6 `
id=`   echo $cdate | cut -c 7-8 `
ih=`   echo $cdate | cut -c 9-10 `

echo 'yyyy = ' ${yyyy}
echo 'yy   = ' ${yy}
echo 'im   = ' ${im}
echo 'ih   = ' ${ih}

domdir=${DATA}/${1}.${cdate}/MESSAGES

# Set paths for runtime and save directories
tmpdir=${DATA}/3DVAR/hwrf_merge/$storm.$cdate
newdat=${DATA}/3DVAR/hwrf_rel/$storm.$cdate
savdir=${DATA}/$storm.${cdate}/ATMOS
bdy_d=${DATA}/$storm.${cdate}/ATMOS_BDY

# Set up directories
rm -rf $tmpdir
mkdir -p $tmpdir
cd $tmpdir

# Copy executable and fixed files to $tmpdir

cp ${EXEChwrf}/hwrf_diffwrf_3dvar     ./hwrf_diffwrf_3dvar.exe
cp ${EXEChwrf}/hwrf_bin_io     ./hwrf_bin_io.exe
cp ${EXEChwrf}/hwrf_inter_2to1 ./hwrf_inter_2to1.x
cp ${EXEChwrf}/hwrf_inter_2to2 ./hwrf_inter_2to2.x
cp ${EXEChwrf}/hwrf_inter_2to6 ./hwrf_inter_2to6.x
cp ${EXEChwrf}/hwrf_guess      ./hwrf_guess.x

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

# Copy wrfnmm restart files

if [ ${INIT} == YES ]; then
    cp $newdat/storm_radius                                      ./storm_radius
else
    cp ${FIXhwrf}/hwrf_storm_radius                                   ./storm_radius
fi

st_depth=${STORM_DEPTH}
echo "storm depth == $st_depth"
if [[ "${GSI}" == YES ]]; then
    infile_d01=${DATA}/3DVAR/outreg/nmm_netcdf/gsi_cvs1.$storm.$cdate/wrfanl.$cdate
    infile_d02=${DATA}/3DVAR/outreg/nmm_netcdf/gsi_cvs2.$storm.$cdate/wrfanl.$cdate
    # infile_d03=${DATA}/3DVAR/outreg/nmm_netcdf/gsi_cvs3.$storm.$cdate/wrfanl.$cdate

    if ( ! $USHhwrf/hwrf_file_complete.pl -w1800 -s1 -S10 -o20 "$infile_d02" ) ; then
        sh ${utilscript}/setup.sh
        err=911
        err_exit "file $infile_d02 not complete after a half hour.  ABORTING"
    fi

    if ( ! $USHhwrf/hwrf_file_complete.pl -w1800 -s1 -S10 -o20 "$infile_d01" ) ; then
        sh ${utilscript}/setup.sh
        err=911
        err_exit "file $infile_d01 not complete after a half hour.  ABORTING"
    fi

    # if ( ! $USHhwrf/hwrf_file_complete.pl -w1800 -s1 -S10 -o20 "$infile_d03" ) ; then
    #     sh ${utilscript}/setup.sh
    #     err=911
    #     err_exit "file $infile_d03 not complete after a half hour.  ABORTING"
    # fi

else
    infile_d01=${newdat}/wrfinput_d01
    infile_d02=${newdat}/wrfghost_d02
fi

if [ ${GSI} == YES ]; then
    cp ${DATA}/3DVAR/outreg/nmm_netcdf/gsi_cvs1.$storm.$cdate/wrfanl.$cdate ./wrfinput_d01
    cp ${DATA}/3DVAR/outreg/nmm_netcdf/gsi_cvs2.$storm.$cdate/wrfanl.$cdate ./wrfghost_d02
else
    cp ${newdat}/wrfinput_d01 ./wrfinput_d01
    cp ${newdat}/wrfghost_d02 ./wrfghost_d02
fi

cp $savdir/wrfanl_d02_${yyyy}-${im}-${id}_${ih}:00:00       ./wrfinput_d02

testf_d03=$savdir/wrfanl_d03_${yyyy}-${im}-${id}_${ih}:00:00

if [ -f $testf_d03 ]; then
    cp $testf_d03 ./wrfinput_d03
fi

if [ $IO_FORM = 2 ]; then

    ./hwrf_diffwrf_3dvar.exe storm_relocate wrfinput_d01 flnm3 new_hdas_d01

else
    echo $tmpdir                 > itag1
    echo "wrfinput_d01"         >> itag1
    echo "relocate"             >> itag1
    echo $tmpdir/new_hdas_d01   >> itag1
    echo $domdir/domain.center  >> itag1
    sh ${utilscript}/setup.sh

    $USHhwrf/hwrf_run.sh -mpiwrap ./hwrf_bin_io.exe < itag1 > stdout_wrfges1 2>&1

    export err=$? 
    echo "executable hwrf_bin_io return err = ${err}"
    if [ $err -ne 0 ]; then
        err_exit "executable hwrf_bin_io return err = ${err}"
    fi
fi

cp ${savdir}/namelist_analysis0.input ./namelist.input
if [ $IO_FORM = 2 ]; then

    ./hwrf_diffwrf_3dvar.exe storm_relocate wrfinput_d02 flnm3 new_gfs_d02

  if [ -f $testf_d03 ]; then
    ./hwrf_diffwrf_3dvar.exe storm_relocate wrfinput_d03 flnm3 new_gfs_d03
  fi
else

    echo $tmpdir                 > itag2
    echo "wrfinput_d02"         >> itag2
    echo "relocate"             >> itag2
    echo $tmpdir/new_gfs_d02    >> itag2
    echo $domdir/domain.center  >> itag2
    sh ${utilscript}/setup.sh

    $USHhwrf/hwrf_run.sh -mpiwrap ./hwrf_bin_io.exe < itag2 > stdout_wrfges2 2>&1

    export err=$?
    echo "executable hwrf_bin_io return err = ${err}"
    if [ $err -ne 0 ]; then
        err_exit "executable hwrf_bin_io return err = ${err}"
    fi
    if [ -f $testf_d03 ]; then
        echo $tmpdir                 > itag3
        echo "wrfinput_d03"         >> itag3
        echo "relocate"             >> itag3
        echo $tmpdir/new_gfs_d03    >> itag3
        echo $domdir/domain.center  >> itag3
        sh ${utilscript}/setup.sh
        
        $USHhwrf/hwrf_run.sh -mpiwrap ./hwrf_bin_io.exe < itag3 > stdout_wrfges3 2>&1
        
        export err=$?
        echo "executable hwrf_bin_io return err = ${err}"
        if [ $err -ne 0 ]; then
            err_exit "executable hwrf_bin_io return err = ${err}"
        fi
    fi
fi

cp ${savdir}/namelist_ghost.input ./namelist.input

if [ $IO_FORM = 2 ]; then

    ./hwrf_diffwrf_3dvar.exe storm_relocate wrfghost_d02 flnm3 new_ght_d02

else

    echo $tmpdir                 > itag4
    echo "wrfghost_d02"         >> itag4
    echo "relocate"             >> itag4
    echo $tmpdir/new_ght_d02    >> itag4
    echo $domdir/domain.center  >> itag4

    sh ${utilscript}/setup.sh
    $USHhwrf/hwrf_run.sh -mpiwrap ./hwrf_bin_io.exe < itag4 > stdout_wrfges4 2>&1

    export err=$?
    echo "executable hwrf_bin_io return err = ${err}"
    if [ $err -ne 0 ]; then
        err_exit "executable hwrf_bin_io return err = ${err}"
    fi
fi


ln -s -f $tmpdir/new_ght_d02                 fort.26
ln -s -f $tmpdir/new_gfs_d03                fort.36
ln -s -f $tmpdir/data_merge_d03           fort.56

export gesfhr=6

# run the executable hwrf_inter_2to1
sh ${utilscript}/setup.sh
export pgm=hwrf_inter_2to1.x
. prep_step
startmsg
echo $gesfhr | $tmpdir/hwrf_inter_2to1.x
export err=$?; err_chk
echo "executable hwrf_inter_2to1.x return code err = ${err}"
if [ $err -ne 0 ]; then
    err_exit "executable hwrf_inter_2to1.x return code err = ${err}"
fi

rm -f fort.*
rm -f $tmpdir/flag_file

ln -s -f $tmpdir/new_ght_d02                 fort.26
ln -s -f $tmpdir/new_gfs_d02                fort.36
ln -s -f $tmpdir/new_hdas_d01                fort.46
ln -s -f $tmpdir/data_merge_d02           fort.56

export gesfhr=6

# run the executable hwrf_inter_2to2
sh ${utilscript}/setup.sh
export pgm=hwrf_inter_2to2.x
. prep_step
startmsg
echo $gesfhr | $tmpdir/hwrf_inter_2to2.x
export err=$?; err_chk
echo "executable hwrf_inter_2to2.x return code err = ${err}"
if [ $err -ne 0 ]; then
    err_exit "executable hwrf_inter_2to2.x return code err = ${err}"
fi

rm -f fort.*
rm -f $tmpdir/flag_file


ln -s -f $tmpdir/new_hdas_d01                   fort.46
ln -s -f $tmpdir/new_gfs_d02                    fort.26
ln -s -f $tmpdir/new_ght_d02                    fort.36
ln -s -f $tmpdir/storm_radius                   fort.85

ln -s -f $tmpdir/data_merge_d01                 fort.56

export gesfhr=6

# run the executable hwrf_inter_2to6
sh ${utilscript}/setup.sh
export pgm=hwrf_inter_2to6.x
. prep_step
startmsg
echo $gesfhr | $tmpdir/hwrf_inter_2to6.x
export err=$?; err_chk
echo "executable hwrf_inter_2to6.x return code err = ${err}"

if [ $err -ne 0 ]; then
    err_exit "executable hwrf_inter_2to6.x return code err = ${err}"
fi

rm -f itag1 itag2 itag3 itag4

if [ $IO_FORM = 2 ]; then

    ./hwrf_diffwrf_3dvar.exe 3dvar_update wrfinput_d01 data_merge_d01
else
    echo $tmpdir                  > itag1
    echo "wrfinput_d01"          >> itag1
    echo "update"                >> itag1
    echo $tmpdir/data_merge_d01  >> itag1
    echo $domdir/domain.center   >> itag1

    sh ${utilscript}/setup.sh
    $USHhwrf/hwrf_run.sh -mpiwrap ./hwrf_bin_io.exe < itag1 > stdout_wrfges5 2>&1

    export err=$?; err_chk
    echo "executable hwrf_bin_io return err = ${err}"
fi

cp ${savdir}/namelist_analysis0.input ./namelist.input
if [ $IO_FORM = 2 ]; then

    ./hwrf_diffwrf_3dvar.exe 3dvar_update wrfinput_d02 data_merge_d02

    if [ -f $testf_d03 ]; then
        ./hwrf_diffwrf_3dvar.exe 3dvar_update wrfinput_d03 data_merge_d03
    fi

else

    echo $tmpdir                  > itag2
    echo "wrfinput_d02"          >> itag2
    echo "update"                >> itag2
    echo $tmpdir/data_merge_d02  >> itag2
    echo $domdir/domain.center   >> itag2

    sh ${utilscript}/setup.sh
    $USHhwrf/hwrf_run.sh -mpiwrap ./hwrf_bin_io.exe < itag2 > stdout_wrfges6 2>&1

    export err=$?; err_chk
    echo "executable hwrf_bin_io return err = ${err}"
    if [ $err -ne 0 ]; then
        err_exit "executable hwrf_bin_io return err = ${err}"
    fi

  if [ -f $testf_d03 ]; then
    echo $tmpdir                  > itag3
    echo "wrfinput_d03"          >> itag3
    echo "update"                >> itag3
    echo $tmpdir/data_merge_d03  >> itag3
    echo $domdir/domain.center   >> itag3

    sh ${utilscript}/setup.sh
    $USHhwrf/hwrf_run.sh -mpiwrap ./hwrf_bin_io.exe < itag3 > stdout_wrfges7 2>&1

    export err=$?; err_chk
    echo "executable hwrf_bin_io return err = ${err}"
    if [ $err -ne 0 ]; then
        err_exit "executable hwrf_bin_io return err = ${err}"
    fi
  fi

fi

mv $savdir/wrfinput_d01 $savdir/wrfinput_d01_org
mv $savdir/wrfanl_d02_${yyyy}-${im}-${id}_${ih}:00:00 $savdir/wrfanl_d02_org
cp $tmpdir/wrfinput_d01 $savdir/wrfinput_d01
cp $tmpdir/wrfinput_d02 $savdir/wrfanl_d02_${yyyy}-${im}-${id}_${ih}:00:00

if [ -f $testf_d03 ]; then
  mv $savdir/wrfanl_d03_${yyyy}-${im}-${id}_${ih}:00:00 $savdir/wrfanl_d03_org
  cp $tmpdir/wrfinput_d03 $savdir/wrfanl_d03_${yyyy}-${im}-${id}_${ih}:00:00
fi

if [ -f $savdir/wrfinput_d01 ]; then
    if [ -f $savdir/wrfanl_d02_${yyyy}-${im}-${id}_${ih}:00:00 ]; then

        if [[ "$MERGE_SUBMITS_FORECAST" != NO ]] ; then
            echo "Successful completion of 3DVAR initialization procedure"
            echo "Modifed HWRF input files for PARENT, $savdir/wrfinput_d01"
            echo "and for NEST, $savdir/wrfanl_d02_${yyyy}-${im}-${id}_${ih}:00:00"
            echo "are succesfully produced.  Will now wait for boundary files"
            echo "from real step 2 in $bdy_d/wrfbdy*"
        else
            echo "Successful completion of 3DVAR initialization procedure"
            echo "Modifed HWRF input files for PARENT, $savdir/wrfinput_d01"
            echo "and for NEST, $savdir/wrfanl_d02_${yyyy}-${im}-${id}_${ih}:00:00"
            echo "are succesfully produced.  HWRF Model can now be run using these"
            echo "input files and BCs obtained from hwrf_prep_hybrid_step1.sh and"
            echo "hwrf_prep_hybrid_step2.sh scripts"
            exit 0
        fi

    fi

else

echo "hwrf_merge.sh failed, check the path names and status of the scripts"
echo "hwrf_relocate_step1.sh, hwrf_relocate_step2.sh, hwrf_nmm_gsi_d1.sh"
echo "and hwrf_nmm_gds_d2.sh, now exiting without submitting the model run"

    sh ${utilscript}/setup.sh
    err=911
err_exit "hwrf_merge.sh failed - exiting without submitting the model run"

fi

    # Wait for the real step 2 to create the boundary file
    # We only get here if $MERGE_SUBMITS_FORECAST == YES
    if ( ! $USHhwrf/hwrf_file_complete.pl -s1 -S20 -w 1800 -o 30 "$bdy_d/wrfbdy*" ) ; then
        msg="BOUNDARY FILE $bdy_d/wrfbdy* is not created."
        echo $msg
        err_exit "$msg"
    fi
    
    /bin/cp -pf $bdy_d/wrfbdy* $savdir/
    
    echo "WRF boundary files are now also available."
    echo
    echo "HWRF Model can now be run using input files from this script and boundary"
    echo "files from real step2."
