#!/bin/sh
###############################################################################
#                                                                             #
# This script finds and copies an NAM file for the wave model.                #
#                                                                             #
# This version extract SST, TAIR, UGRD and VGRD information from the grib     #
# NAM output file in the AWLDAS grid (110), lat/lon at 0.125 deg resolution.  #
#                                                                             #
# Remarks :                                                                   #
# - This script runs in the work directory designated in the mother script in #
#   which it generates its own sub-directory 'nam_yyyymmddhh'. If all is well #
#   the directory is removed at the end of the script.                        #
# - The time group yyyymmddhh is the first parameter passed to the script.    #
# - See section 0.c for variables that need to be set.                        #
#                                                                             #
#                                                                July, 2007   #
#                                                                             #
###############################################################################
#
# --------------------------------------------------------------------------- #
# 0.  Preparations
# 0.a Basic modes of operation

  cd $DATA
  seton='+xa'
  setoff='+xa'
  set $seton

  rm -rf ndfd_$1
  mkdir ndfd_$1
  cd ndfd_$1

  count=$2
  hdr=$3

  set $setoff
  echo ' '
  echo '+--------------------------------+'
  echo '!     Find and copy ndfd files    |'
  echo '+--------------------------------+'
  set $seton

# 0.b Check if time set

  if [ "$#" -lt '1' ]
  then
    set $setoff
    echo ' '
    echo '***************************************'
    echo '*** TIME IN multiwavendfd.sh NOT SET ***'
    echo '***************************************'
    echo ' '
    set $seton
    ../postmsg "$jlogfile" " TIME IN multiwavendfd.sh NOT SET"
    exit 1
  else
    ymdh=$1
    set $setoff
    echo "   Time            : $ymdh"
    echo ' '
    set $seton
  fi

# 0.c The tested variables should be exported by the calling script.

  if [ -z "$utilexec" ] || [ -z "$COMNDFD" ]
  then
    set $setoff
    echo ' '
    echo '**********************************'
    echo '*** EXPORTED VARIABLES NOT SET ***'
    echo '**********************************'
    echo ' '
    ../postmsg "$jlogfile" " EXPORTED VARIABLES NOT SET."
    exit 1
    set $seton
  fi

# --------------------------------------------------------------------------- #
# 1. Copy the wind file data 

  start=1
  ymdh_loop=$ymdh
  ndfdOK='no'

  while [ "$ndfdOK" = 'no' ] && [ "$start" -le '144' ]
  do

    ymdht=`$utilexec/ndate -1 $ymdh_loop`
    ymdhe=`$utilexec/ndate -4 $ymdh_loop`

    while [ "$ndfdOK" = 'no' ] && [ $ymdht -ge $ymdhe ]
    do

      ymdht=`$utilexec/ndate -1 $ymdht`
      ymd=`echo $ymdht | cut -c1-8`
      ext=`echo $ymdht | cut -c9-10`

      if [ -f $COMNDFD/$ymd/wgrbbul/ndfd_gl_${ext}.grib2 ]
      then
        ndfd_file=ndfd_gl_${ext}.grib2

        cp $COMNDFD/$ymd/wgrbbul/$ndfd_file . > getndfd.out 2> getndfd.err
        err=$?

        if [ "$err" != '0' ]
        then
          cat getndfd.out
          cat getndfd.err
          set $setoff
          echo ' '
          echo '****************************************'
          echo '*** FATAL ERROR IN copying grib data ***'
          echo '****************************************'
          echo ' '
          set $seton
          ../postmsg "$jlogfile" "ERROR IN copying grib data for $ymdh"
        fi

        rm -f getnam.out getnam.err

# --------------------------------------------------------------------------- #
# 1b. Extract grib data

        rm -f *.txt
        rm -f *.dat

        record_no1=`$utilexec/wgrib2 $ndfd_file -match WIND -vt | grep ${ymdh} | cut -f1 -d:` 
        record_no2=`$utilexec/wgrib2 $ndfd_file -match WDIR -vt | grep ${ymdh} | cut -f1 -d:` 

        if [ "$record_no1" -gt '0' ] && [ "$record_no2" -gt '0' ]
        then
          ndfdOK='yes'
          set $setoff
          echo ' '
          echo " Wind data found in $COMNDFD/$ymd/wgrbbul/$ndfd_file"
          echo " Extracting record number $record_no1"
          echo ' '
          set $seton

#          $utilexec/wgrib2 $ndfd_file -match WIND -vt | grep ${ymdh} | $utilexec/wgrib2 -i $ndfd_file -d 1 -rpn "sto_1:9999.99:rcl_1:merge" -spread wspd.txt > tmp.txt
#          $utilexec/wgrib2 $ndfd_file -match WDIR -vt | grep ${ymdh} | $utilexec/wgrib2 -i $ndfd_file -d 1 -rpn "sto_1:9999.99:rcl_1:merge" -spread wdir.txt > tmp2.txt

          $utilexec/wgrib2 $ndfd_file -match ":(WIND|WDIR):" -match ":vt=${ymdh}" -rpn "sto_1:9999.99:rcl_1:merge" -if ":WIND:" -spread wspd.txt -if ":WDIR:" -spread wdir.txt | head -n 1 > tmp.txt 
          
          sed 's/d=/ /' tmp.txt | awk '{ print $2}' | cut -f 1,4 -d : | sed 's/:/ /' > stamp.txt

        fi

      fi

    done

    if [ "$ndfdOK" = 'no' ]
    then
      set $setoff
      echo ' '
      echo " Could not find wind data in loop $ymdh_loop, moving back ..." 
      echo ' '
      set $seton
      ymdh_loop=`$utilexec/ndate -3 $ymdh_loop`
      start=`expr $start + 1`
    fi

  done

# --------------------------------------------------------------------------- #
# 1c. Convert to waveprep format

  if [ "$ndfdOK" = 'yes' ]
  then

     echo $count > tmp.out

     $EXECwave/convert_ndfd < tmp.out > convert.out
     OK=$?

     if [ "$OK" != 0 ]
     then
       set $setoff
       echo ' '
       echo '***************************************************************'
       echo "*** Fatal Error : Could not convert grib2 files for ${ymdh} ***" 
       echo '***************************************************************'
       echo ' '
       cat convert.out
       ndfdOK='no'
     fi

  else
     set $setoff
     echo ' '
     echo '*************************************************'
     echo "*** EROOR: NO NDFD WINDS FOUND FOR CYCLE $ymdh***"
     echo '*************************************************'
     echo ' '
     set $seton
     ../postmsg "$jlogfile" "NDFD winds not found for $ymdh in multiwavendfd.sh"
  fi

# --------------------------------------------------------------------------- #
# 2. run waveprep 

  if [ "$ndfdOK" = 'yes' ]
  then

# 2.a Prepare the input file

    sed -e "s/HDR/$hdr/g" ../multiwaveprep.ndfd_inc.tmpl > multiwaveprep.inp

# 2.b Execute code

    for grdID in $grids
    do 

      cp ../mod_def.$grdID mod_def.ww3
      
      $EXECwave/multiwaveprep 
      err=$?

      if [ "$err" != '0' ]
      then
        set $setoff
        echo ' '
        echo '*****************************************'
        echo '*** FATAL ERROR IN EXECUTING WAVEPREP ***'
        echo '*****************************************'
        echo ' '
        ../postmsg "$jlogfile" "ERROR IN EXECUTING WAVEPREP FOR $ymdh."
        set $seton
        ndfdOK='no'
      else
        if [ ! -f wind.ww3 ]
        then
          set $setoff
          echo ' '
          echo '****************************************'
          echo '*** FATAL ERROR : wind.ww3 NOT FOUND ***'
          echo '****************************************'
          echo ' '
          ../postmsg "$jlogfile" "ERROR IN EXECUTING WAVEPREP FOR $ymdh."
          set $seton
          ndfd_ok='no'
        else
          set $setoff
          echo ' '
          echo " Run succesful moving wind file ..."
          set $seton
          mv -f wind.ww3 ../wind.$grdID.$ymdh
        fi
      fi

    done
  
  else
    set $setoff
    echo ' '
    echo '**************************************************'
    echo '*** FATAL ERROR : COULD NOT GENERATE wind file ***'
    echo '**************************************************'
    echo ' '
    ../postmsg "$jlogfile" "COULD NOT EXTRACT WIND FOR $ymdh."
    set $seton
  fi

# --------------------------------------------------------------------------- #
# 3.  Clean up the directory

  if [ "$ndfdOK" = 'yes' ]
  then
    set $setoff
    echo ' '
    echo "   Removing work directory after success."
    set $seton

    cd ..
    rm -rf ndfd_$ymdh

  fi

  set $setoff
  echo ' '
  echo 'End of multiwavendfd_inc.sh at'
  date

# End of multiwavendfd.sh ---------------------------------------------------- #
