#!/bin/sh
###############################################################################
#                                                                             #
# This script grabs the altimeter data from the tanks and develops the        #
# collocated model output along the altimeter tracks. It is run as a child    #
# script by an archiving script.                                              #
#                                                                             #
# Remarks :                                                                   #
#   - The necessary files are retreived by the mother script                  #
#   - The script is called once for each altimeter instrument                 #
#   - This script runs in the work directory designated in the mother script  #
#                                                                             #
#                                                                 May 2007    #
# Last update : 05-29-2007                                                    #
#                                                                             #
###############################################################################

# --------------------------------------------------------------------------- 
# 0. Initialization
# 0.a Basic modes

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

  cd $DATA

  inst=$1
  adate=$2

  rm -f altm_$1
  mkdir altm_$1
  
  cd altm_$1

  set $setoff
  echo ' '
  echo '+---------------------------+'
  echo '!   Unpack altimeter data   |'
  echo '+---------------------------+'
  echo "         Instrument : $inst"
  echo "         Date       : $adate"
  set $seton

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

  if [ -z "$EXECwave" ] || [ -z "$USHwave" ] || [ -z "$utilexec" ] || \
     [ -z "$arclog" ] || [ -z "$grids" ] || [ -z "$com" ] || [ -z "$RUN" ] || \
     [ -z "$date" ] || [ -z "$cycle" ] || [ -z "$modID" ]
  then
    set $setoff
    echo ' '
    echo '******************************************************'
    echo '*** EXPORTED VARIABLES NOT SET in multiwavealtim.sh***'
    echo '******************************************************'
    echo ' '
    exit 1
    set $seton
  fi

# 0.c Check command line arguments

  if [ -z "$adate" ]
  then
    set $setoff
    echo ' '
    echo '*****************************************'
    echo '*** DATE IN multiwavealtim.sh NOT SET ***'
    echo '*****************************************'
    echo ' '
    set $seton
    exit 1
  else
    $utilexec/ndate 0 ${adate}00 > /dev/null #2> /dev/null
    OK=$?

    if [ "$OK" != '0' ]
    then
      set $setoff
      echo ' '
      echo '************************************************'
      echo '*** DATE IN multiwavealtim.sh NOT RECOGNIZED ***'
      echo '************************************************'
      echo ' '
      set $seton
      exit 2
    fi
  fi

  case $inst in
    'jas' )  alt_file=/dcom/us007003/$adate/b031/xx106 ; decoder=jas_decoder ;;
    'gfo' )  alt_file=/dcomdev/us007003/$adate/b031/xx107 ; decoder=gfo_decoder ;;
      *   )  set $setoff ;
             echo ' ' ;
             echo '********************************************' ;
             echo "*** INSTRUMENT TYPE $inst NOT RECOGNIZED ***" ; 
             echo '********************************************' ;
             echo ' ' ;
             set $seton ;
             exit 3 ;;
  esac

# --------------------------------------------------------------------------- #
# 1.  Pick up data from tank

  set $setoff
  echo "                   File : $alt_file"
  set $seton

  if [ -f $alt_file ]
  then
    cp $alt_file $inst.buffr 
  fi

  if [ ! -f $inst.buffr ]
  then
    set $setoff
    echo ' '
    echo '***************************'
    echo '*** DATA FILE NOT FOUND ***'
    echo '***************************'
    echo ' '
    set $seton
    exit 4
  fi

# --------------------------------------------------------------------------- #
# 2.  Running programs
# 2.a Running decoder

  set $setoff
  echo ' '
  echo '   Running decoder ...'
  set $seton

  export XLFRTEOPTS="unit_vars=yes"
  export XLFUNIT_12="$inst.buffr"
  export XLFUNIT_52="$inst.$adate"
  export XLFUNIT_53="$inst.raw"

  $EXECwave/$decoder > decode_$inst.out 2>&1
  OK=$?

  if [ "$OK" != '0' ] || [ ! -f $inst.raw ]
  then
    set $setoff
    echo ' '
    echo '************************'
    echo '*** ERROR IN decoder ***'
    echo '************************'
    echo ' '
    set $seton
    cat decode_$inst.out
    rm -f decode_$inst.out
    exit 5
  fi

  rm -f $inst.buffr decode_$inst.out

# 2.b Running converter

  set $setoff
  echo '   Running converter ...'
  set $seton

  $EXECwave/convrtalt < $inst.raw > $inst.unsorted
  OK=$?

  if [ "$OK" != '0' ] || [ ! -f $inst.unsorted ]
  then
    set $setoff
    echo ' '
    echo '**************************'
    echo '*** ERROR IN convrtalt ***'
    echo '**************************'
    echo ' '
    set $seton
    exit 6
  fi

  rm -f $inst.raw

# 2.c Sort data file

  set $setoff
  echo '   Running sort ...'
  set $seton

  sort -u $inst.unsorted >> $inst.$adate

  rm -f $inst.unsorted

# --------------------------------------------------------------------------- #
# 3. Initialization for model - data collocation
# 3.a Check for data

 if [ ! -f $inst.$adate ]
 then
    set $setoff
    echo ' '
    echo '******************************************'
    echo '*** ERROR IN EXTRACTING ALTIMETRY DATA ***'
    echo '******************************************'
    echo ' '
    set $seton
    exit 7
  fi

# 3.b Setting periods

  periods='HIND F000H F024H F048H F072H F096H F120H'  

# --------------------------------------------------------------------------- #
# 4. Set up looping for collocations ...
# 4.a Loop over grids 
#     Run interval hardwired to 6 hours
#     Field intervals hardwired to 1 hour

   ymdh_beg=${adate}00
   ymdh_end=`$utilexec/ndate 24 $ymdh_beg`

   cp ../multiwaveflds.trans.tmpl .

   cp $inst.$adate alt.data

  for grdID in $grids
  do

# 4.a.1 Get the appropriate fixed files

    ln -sf ../mod_def.$grdID mod_def.ww3

    if [ ! -f mod_def.ww3 ]
    then
      set $setoff
      echo "            *** File not found ***"
      echo "$modID arch $grdID $date $cycle : Fixed file missing in multiwavealtim.sh ($period)" >> $arclog
      set $seton
      exit 8
    fi

# 4.b Loop over periods

    for period in $periods
    do


# 4.b.1 Setting up time management for particular period

      case $period in 
        'HIND'  ) first='-9'  ; last='-3' ;;
        'F000H' ) first='-3'  ; last=3 ;;
        'F024H' ) first=21    ; last=27 ;;
        'F048H' ) first=45    ; last=51 ;;
        'F072H' ) first=69    ; last=75 ;;
        'F096H' ) first=93    ; last=99 ;;
        'F120H' ) first=117   ; last=123 ;;
          *     ) echo "period ID $period not recognized" 2>&1 ; exit 9 ;;
      esac

      offset=`expr $first  + $last`
      offset=`expr $offset / 2`
      delta=`expr $offset - $first`

      set $setoff
      echo ' '
      echo "Processing data for grid $grdID and forecast time $period :"
      echo "----------------------------------------------------------"
      echo "   Time frame from $first to $last hours ($offset +- $delta)."
      set $seton

      if [ "$first" -gt '0' ]
      then
        ifirst=-$first
      else
        ifirst=`echo $first | sed "s/-//g"`
      fi

      ymdhc=`$utilexec/ndate $ifirst ${adate}00`
      datec=`echo $ymdhc | cut -c1-8`
      hourc=`echo $ymdhc | cut -c9-10`

      file="$modID.$grdID.$period.$adate.$inst.raw"

# 4.c Loop over the runs in the period

      dater=$datec
      if [ "$hourc" -ge '18' ]
      then
        cycr=18
      else
        if [ "$hourc" -ge '12' ]
        then
          cycr=12
        else
          if [ "$hourc" -ge '06' ]
          then
            cycr=06
          else
            cycr=00
          fi
        fi
      fi
      cycler=t${cycr}z
      ymdhr=$dater$cycr
      ymdh0=`$utilexec/ndate $first $ymdhr`
      ymdhn=`$utilexec/ndate $last $ymdhr`

# 4.c.1 Begin loop over runs for a 24 hour period

      while [ "$ymdh0" -lt "$ymdh_end" ]
      do

        if [ "$ymdh0" -lt "$ymdh_beg" ]
        then
          ymdh0=$ymdh_beg
        fi
        if [ "$ymdhn" -gt "$ymdh_end" ]
        then
          ymdhn=$ymdh_end
        fi

        ymdht=$ymdh0
        nfields=1
        while [ "$ymdht" -lt "$ymdhn" ]
        do
          nfields=`expr $nfields + 1`
          ymdht=`$utilexec/ndate 1 $ymdht`
        done

        set $setoff
        echo "      Data from $ymdh0 to $ymdhn from $dater $cycler run ($nfields fields)."
        set $setoff

        time0="`echo $ymdh0 | cut -c1-8` `echo $ymdh0 | cut -c9-10`0000"
        timen="`echo $ymdhn | cut -c1-8` `echo $ymdhn | cut -c9-10`0000"

# 4.c.2 Copying the model data file

        set $setoff
        echo "  Copying data from $com/${RUN}.$dater/$modID.$grdID.$cycler.outgrd to out_grd.ww3"
        set $seton

        rm -f out_grd.ww3
        if [ -f $com/${RUN}.$dater/$modID.$grdID.$cycler.outgrd ]
        then
          cp $com/${RUN}.$dater/$modID.$grdID.$cycler.outgrd out_grd.ww3
        fi

        if [ ! -f out_grd.ww3 ]
        then

          set $setoff
          echo "            *** File not found ***"
          echo "$modID arch $grdID $date $cycle : Raw output file missing in multiwavealtim.sh ($period)" >> $arclog
          set $seton

        else

# 4.c.3 Extract fields

          rm -f multiwaveflds.inp
          rm -f ww3.????????.hs
          rm -f ww3.????????.wnd

          sed -e "s/TIME/$time0/g"                                  \
              -e "s/DELTA/3600./g"                                  \
              -e "s/NFIELDS/$nfields/g"                             \
              -e "s/FLAGS/F F T F F  T F F F F  F F F F F  F F F F F  F F F F F F F F F F F/g" \
                                    multiwaveflds.trans.tmpl > multiwaveflds.inp

          $EXECwave/multiwaveflds > multiwaveflds.out 2>&1
          OK=$?

          rm -f multiwaveflds.inp
          rm -f out_grd.ww3

          nr_hs=`ls ww3.*.hs 2> /dev/null | wc -l | awk '{ print $1}'`
          nr_wnd=`ls ww3.*.wnd 2> /dev/null | wc -l | awk '{ print $1}'`

          if [ "$OK" != '0' ] || [ "$nr_hs" != "$nfields" ] \
                                 [ "$nr_wnd" != "$nfields" ]
          then

            echo "         *** Error in multiwaveflds *** "
            echo ' '
            cat multiwaveflds.out ; rm -f multiwaveflds.out
            echo "$modID arch $grdID $date $cycle : error multiwaveflds in multiwavealtim.sh ($period)" >> $arclog

          else

            rm -f multiwaveflds.out

# 4.c.4 Collocate model with altimeter 

            set $setoff
            echo "         Collocate model fields with altimeter."
            set $seton

            echo $time0 $timen 2 | $EXECwave/alt_col > alt_col.out 2>&1
            OK=$?

            rm -f ww3.????????.hs
            rm -f ww3.????????.wnd

            if [ "$OK" != '0' ]
            then

              echo "*** Error in alt_col for $grdID $period $inst*** "
              echo ' '
              cat alt_col.out
              echo "$modID arch $grdID $date $cycle : error alt_col in multiwavealtim.sh ($period)" >> $arclog

            else
          
             set $setoff
             echo "         Add to file $file "
             set $seton
   
             cat collocations >> $file
             rm -f collocations

            fi

            rm -f alt_col.out

# ... End of if check in section 4.c.3
    
          fi

# ... End of if check in section 4.c.2

        fi

# 4.c.5 Update time to move to next cycle for the same period

        ymdhr=`$utilexec/ndate 6 $ymdhr`
        ymdh0=`$utilexec/ndate $first $ymdhr`
        ymdhn=`$utilexec/ndate $last $ymdhr`
        dater=`echo $ymdhr | cut -c1-8`
        cycler=t`echo $ymdhr | cut -c9-10`z

      done 

# 4.d Clean up

      if [ -f $file ]
      then
        set $setoff
        echo "      Copy $file to raw data directory"
        set $setoff
        mv $file ../raw/.
      fi

# ... End of loop over periods starting in section 4.b
 
    done

    rm -f mod_def.ww3

# ... End of loop over grids starting in section 4.a

  done

  rm -f alt.data
  rm -f waveflds.inp.tmpl

# --------------------------------------------------------------------------- #
# 5 Clean up 

  set $setoff
  echo ' '
  echo "   Removing work directory after success."
  set $seton

  mv $inst.$adate ../raw/.
  cd ../
  rm -rf altm_$inst

  set $setoff
  echo ' '
  echo 'End of multiwavealtim.sh'
  date

#-------------------End of multiwavealtim.sh----------------------------------#
