#!/bin/ksh
##################################################################
# hwrf_aux_rw.sh 
################
# This script is used in coupling with the WAVE MODEL   
#######################
# Original Script: Young Kwon and Vijay Tallapragada
# April 2007
# Modified Executable for 2008: Young Kwon and Vijay Tallapragada
# April 2008
# Script modifications for 2009 HWRF implementation - Vijay Tallapragada
# June 2009
# Modified for V3.2 WRF by Sam Trahan
# October 2010
##################################################################
set -x
######### GET THE INPUT VARIABLES ###################

if [ $# -eq 6 ]
    then 
    export storm=${1}
    export YEAR=${2}
    export MONTH=${3}
    export DAY=${4}
    export CYCLE=${5}
    export MODEL=${6}

    echo 'storm = ' ${storm}
    echo 'YEAR  = ' ${YEAR}
    echo 'MONTH = ' ${MONTH}
    echo 'DAY   = ' ${DAY}
    echo 'CYCLE = ' ${CYCLE} 
    echo 'MODEL = ' ${MODEL} 
else
    echo 'USAGE: sh hwrf_aux_rw.sh storm YEAR MONTH DAY CYCLE MODEL'  
    echo 'NEED SIX ARGUMENTS'
    echo 'SCRIPT WILL EXIT'
    sh ${utilscript}/setup.sh
    err=911
    err_exit " SCRIPT NEEDS SIX ARGUMENTS - ABNORMAL EXIT"
fi

function now {
    date +%s
}

function waitfile {
    if [[ "$PARAFLAG" == YES ]] ; then
        set -x
      available=no
      start=$( now )
      giveup=$(( start + 5400 ))
      while [[ $( now ) -lt "$giveup" ]] ; do
          # Wait until the output file is available:
          if ( $USHhwrf/hwrf_file_complete.pl -s 300000 -S1 -o 30 -w 60 "$1*" ) ; then
              echo "FILE $1* IS AVAILABLE"
              available=yes
              break
          fi
          if [[ "$PARAFLAG" == YES ]] ; then
              $USHhwrf/hwrf_port_checksig.sh
          fi
      done
      
      if [[ "$available" != yes ]] ; then
          echo "There is a problem with the model run, aux files $1* are not created"
          echo 'Check if the model is running fine, now exiting'
          sh ${utilscript}/setup.sh
          err=911
          err_exit "aux files $1* are not created"
      fi
      if [[ "$PARAFLAG" == YES ]] ; then
          $USHhwrf/hwrf_port_checksig.sh
      fi
    else
        set -x
        available=no
        # No need to run $USHhwrf/hwrf_port_checksig.sh in operations, so:
        if ( $USHhwrf/hwrf_file_complete.pl -s 300000 -S1 -o 30 -w 5400 "$1*" ) ; then
              echo "FILE $1* IS AVAILABLE"
              available=yes
              break
        fi
        if [[ "$available" != yes ]] ; then
          echo "There is a problem with the model run, aux files $1* are not created"
          echo 'Check if the model is running fine, now exiting'
          sh ${utilscript}/setup.sh
          err=911
          err_exit "aux files $1* are not created"
        fi
    fi
}

function run_aux_rw {
    ./aux_rw.exe
    export err=$?;err_chk
}

######################################################
# set utilities paths
ndate=${utilexec}/ndate

DATE=${YEAR}${MONTH}${DAY}${CYCLE}
echo 'DATE = ' ${DATE}  

if [ $PARAFLAG = YES ]; then
    sl_sec=1
else
    sl_sec=15
fi
# set directory paths

if [ $MODEL = ATMOS ]; then
    tmpdir=${DATA}/${storm}.${DATE}/ATMOS_FCST
else
    tmpdir=${DATA}/${storm}.${DATE}/COUPLED_FCST
fi

outdir1=${DATA}/${storm}.${DATE}/WAVEM_d01/
outdir2=${DATA}/${storm}.${DATE}/WAVEM_d02/
outdir3=${DATA}/${storm}.${DATE}/WAVEM_d03/
echo 'tmpdir  = ' ${tmpdir}
echo 'outdir1 = ' ${outdir1}
echo 'outdir2 = ' ${outdir2}  
echo 'outdir3 = ' ${outdir3}  

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_checksig.sh
fi

# remove directories and remake 
rm -rf $outdir1
rm -rf $outdir2
rm -rf $outdir3
mkdir -p $outdir1
mkdir -p $outdir2
mkdir -p $outdir3

# Wait until output directory is created
avalable=no
start=$( now )
giveup=$(( start + 6000 ))
while [[ $( now ) -lt "$giveup" ]] ; do
    # Wait until the output directory exists
    if ( $USHhwrf/hwrf_file_complete.pl -w60 -S10 -o0 -d "$tmpdir" ) ; then
        echo OUTPUT DIR IS AVAILABLE
        available=yes
        break
    fi
    if [[ "$PARAFLAG" == YES ]] ; then
        $USHhwrf/hwrf_port_checksig.sh
    fi
done

if [[ "$available" != yes ]] ; then
    echo "There is a problem with the model run, $OUTDIR is not created"
    echo 'Check if the model is running fine, now exiting'
    sh ${utilscript}/setup.sh
    err=911
    err_exit "$OUTDIR is not created"
fi

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_checksig.sh
fi

cd ${tmpdir}

# READ THE BINARY HWRF AUX OUTPUT AND WRITE TO PLAIN BINIARY

this_hour=0
final_hour=126
ic=0

while (( this_hour <= final_hour )) ; do
    if [[ "$PARAFLAG" == YES ]] ; then
        $USHhwrf/hwrf_port_checksig.sh
    fi

  echo 'this_hour '$this_hour
  VDATE=`$ndate $this_hour $DATE`
  echo 'VDATE '$VDATE
  YYYY=`echo $VDATE |cut -c1-4`
  MMMM=`echo $VDATE |cut -c5-6`
  DDDD=`echo $VDATE |cut -c7-8`
  HHHH=`echo $VDATE |cut -c9-10`

  VERIF_DATE=$YYYY-$MMMM-$DDDD"_"$HHHH
  echo 'VERIF_DATE '$VERIF_DATE

  if [[ "$this_hour" == 126 ]] ; then
      # Workaround for WRF v3.2 framework bug.  The final output time
      # auxhist1 file is not written out for domain 1, so use the
      # domain 1 history file for hour 126.
      outfile_d01=wrfout_d01_$VERIF_DATE
  else
      outfile_d01=auxhist1_d01_$VERIF_DATE
  fi
  outfile_d02=auxhist1_d02_$VERIF_DATE
  outfile_d03=auxhist1_d03_$VERIF_DATE
  echo $outfile_d01 $outfile_d02 $outfile_d03

  ic=`expr $ic + 1`

  # for d01
  waitfile "${tmpdir}/${outfile_d01}"
  file=`ls -1 ${outfile_d01}*`

  echo 'file '$file

  cp ${EXEChwrf}/hwrf_aux_rw    ./aux_rw.exe   

  cat<<EOF > aux.namelist
&aux
  infile="${tmpdir}/${file}",
  outfile="${outdir1}${ic}",
  ioform=$IO_FORM,
  ! Print verbose diagnostic output for each variable for domain 2 ONLY 
  ! (it would be too slow for domain 1, due to that domain's size):
  diagout=.false.,
/
EOF

  sh ${utilscript}/setup.sh
  export pgm=aux_rw.exe
  . prep_step

  msg="$pgm start for processing d01 aux files"
  postmsg "$jlogfile" "$msg"
  run_aux_rw

  export err=$?;err_chk
  echo "executable aux_rw.exe for ${outdir1}${ic} return code err = ${err}"

  if [[ "$PARAFLAG" == YES ]] ; then
      $USHhwrf/hwrf_port_checksig.sh
  fi

  if [ ${err} -eq 0 ]
      then
      msg="$pgm completed normally"
      postmsg "$jlogfile" "$msg"
  else
      set +x
      echo " "
      echo "!!! ERROR -- An error occurred while running aux_rw.exe for d01, "
      echo "!!! Exiting...."
      echo " "
      set -x
      err_exit " FAILED ${jobid} - ERROR RUNNING aux_rw.exe - ABNORMAL EXIT"
  fi

  # for d02
  waitfile "${tmpdir}/${outfile_d02}"
  file=`ls -1 ${outfile_d02}*`
  echo 'file '$file

  cat<<EOF > aux.namelist
&aux
  infile="${tmpdir}/${file}",
  outfile="${outdir2}${ic}",
  ioform=$IO_FORM,
  ! Print verbose diagnostic output for each variable for domain 2 ONLY 
  ! (it would be too slow for domain 1, due to that domain's size):
  diagout=.true.,
/
EOF

  /bin/cp ${EXEChwrf}/hwrf_aux_rw    ./aux_rw.exe
  sh ${utilscript}/setup.sh 
  export pgm=aux_rw.exe
  . prep_step 

  msg="$pgm start for processing d02 aux files"
  postmsg "$jlogfile" "$msg"
  run_aux_rw

  echo "executable aux_rw.exe for ${outdir2}${ic} return code err = ${err}"

  if [[ "$PARAFLAG" == YES ]] ; then
      $USHhwrf/hwrf_port_checksig.sh
  fi
 
  if [ ${err} -eq 0 ]
      then
      msg="$pgm completed normally"
      postmsg "$jlogfile" "$msg"
  else
      set +x
      echo " "
      echo "!!! ERROR -- An error occurred while running aux_rw.exe for d02, "
      echo "!!! Exiting...."
      echo " "
      set -x
      err_exit " FAILED ${jobid} - ERROR RUNNING aux_rw.exe - ABNORMAL EXIT"
  fi


  # for d03
  waitfile "${tmpdir}/${outfile_d03}"
  file=`ls -1 ${outfile_d03}*`
  echo 'file '$file

  cat<<EOF > aux.namelist
&aux
  infile="${tmpdir}/${file}",
  outfile="${outdir3}${ic}",
  ioform=$IO_FORM,
  ! Print verbose diagnostic output for each variable for domain 2 ONLY 
  ! (it would be too slow for domain 1, due to that domain's size):
  diagout=.true.,
/
EOF

  /bin/cp ${EXEChwrf}/hwrf_aux_rw    ./aux_rw.exe
  sh ${utilscript}/setup.sh 
  export pgm=aux_rw.exe
  . prep_step 

  msg="$pgm start for processing d03 aux files"
  postmsg "$jlogfile" "$msg"
  run_aux_rw

  export err=$?;err_chk
  echo "executable aux_rw.exe for ${outdir3}${ic} return code err = ${err}"

  if [[ "$PARAFLAG" == YES ]] ; then
      $USHhwrf/hwrf_port_checksig.sh
  fi
 
  if [ ${err} -eq 0 ]
      then
      msg="$pgm completed normally"
      postmsg "$jlogfile" "$msg"
  else
      set +x
      echo " "
      echo "!!! ERROR -- An error occurred while running aux_rw.exe for d03, "
      echo "!!! Exiting...."
      echo " "
      set -x
      err_exit " FAILED ${jobid} - ERROR RUNNING aux_rw.exe - ABNORMAL EXIT"
  fi

  this_hour=`expr $this_hour + 1`

done

# APPEND ALL BINARY DATA TO ONE FILE

echo 'total file number should be 127 '$ic

if [ $ic -ne 127 ]; then
    echo 'the number of aux file is not correct should be 127 '$ic
    exit 1
fi

outf='out4wave_d01'

echo $ic                               > auxtag
echo ${outdir1}                        >> auxtag
echo ${outdir1}${outf}                 >> auxtag

# run the executable read_indi_write_all.exe for outdir1 
sh ${utilscript}/setup.sh 
export pgm=hwrf_read_indi_write_all
. prep_step 

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_checksig.sh
fi

msg="$pgm start for processing d01 aux files read-write"
postmsg "$jlogfile" "$msg"

${EXEChwrf}/hwrf_read_indi_write_all < auxtag
export err=$?; err_chk
echo "executable hwrf_read_indi_write_all for outdir1 return code err = ${err}"  

if [ ${err} -eq 0 ]
    then
    msg="$pgm completed normally"
    postmsg "$jlogfile" "$msg"
else
    set +x
    echo " "
    echo "!!! ERROR -- An error occurred while processing d01 $pgm, "
    echo "!!! Exiting...."
    echo " "
    set -x
    err_exit " FAILED ${jobid} - ERROR RUNNING hwrf_read_indi_write_all - ABNORMAL EXIT"
fi

cp ${outdir1}${outf} $tmpdir

outf='out4wave_d02'

echo $ic                               > auxtag
echo ${outdir2}                        >> auxtag
echo ${outdir2}${outf}                 >> auxtag

# run the executable hwrf_read_indi_write_all
sh ${utilscript}/setup.sh 
export pgm=hwrf_read_indi_write_all
. prep_step 
msg="$pgm start for processing d02 aux files read-write"
postmsg "$jlogfile" "$msg"

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_checksig.sh
fi

${EXEChwrf}/hwrf_read_indi_write_all < auxtag
export err=$?; err_chk
echo "executable hwrf_read_indi_write_all for outdir2 return code err = ${err}"  

if [ ${err} -eq 0 ]
    then
    msg="$pgm completed normally"
    postmsg "$jlogfile" "$msg"
else
    set +x
    echo " "
    echo "!!! ERROR -- An error occurred while processing d02 $pgm, "
    echo "!!! Exiting...."
    echo " "
    set -x
    err_exit " FAILED ${jobid} - ERROR RUNNING hwrf_read_indi_write_all - ABNORMAL EXIT"
fi

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_checksig.sh
fi

cp ${outdir2}${outf} $tmpdir


outf='out4wave_d03'

echo $ic                               > auxtag
echo ${outdir3}                        >> auxtag
echo ${outdir3}${outf}                 >> auxtag

# run the executable hwrf_read_indi_write_all
sh ${utilscript}/setup.sh 
export pgm=hwrf_read_indi_write_all
. prep_step 
msg="$pgm start for processing d03 aux files read-write"
postmsg "$jlogfile" "$msg"

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_checksig.sh
fi

${EXEChwrf}/hwrf_read_indi_write_all < auxtag
export err=$?; err_chk
echo "executable hwrf_read_indi_write_all for outdir3 return code err = ${err}"  

if [ ${err} -eq 0 ]
    then
    msg="$pgm completed normally"
    postmsg "$jlogfile" "$msg"
else
    set +x
    echo " "
    echo "!!! ERROR -- An error occurred while processing d03 $pgm, "
    echo "!!! Exiting...."
    echo " "
    set -x
    err_exit " FAILED ${jobid} - ERROR RUNNING hwrf_read_indi_write_all - ABNORMAL EXIT"
fi

if [[ "$PARAFLAG" == YES ]] ; then
    $USHhwrf/hwrf_port_checksig.sh
fi

cp ${outdir3}${outf} $tmpdir

# end of script 
