#!/bin/sh
#
#
# ofs_grib_subdomain.sh - creates subdomain gribs based on domains
#                         read from application table
#
# imported vars:
#    infile - name of infile
#    outfile
#

echo "*** Started script $0"

set -x

# 1.a pull lines to be changed from infile
ioline=`grep iorign $infile`
iorg=`echo $ioline | cut -c2-80`

joline=`grep jorign $infile`
jorg=`echo $joline | cut -c2-80`

ixline=`grep idmp $infile`
idmp=`echo $ixline | cut -c2-80`

jxline=`grep jdmp $infile`
jdmp=`echo $jxline | cut -c2-80`

infile_orig=$infile
outfile_orig=$outfile
outfilesize=${#outfile_orig}


# 2 for each line in the application table
#   - read line
#   - get gridid name and its i,j values
#   - create new infile
#   - gribit 
#   - cat u,v,p latlon 

while read atline
do
  gridid=`echo $atline | cut -d" " -f4`
  if [[ .$gridid !=  . && $gridid != grid_id ]]
  then
     gtline=`grep $gridid $PARMofs/${RUN}_${modID}.grid_table`
     ix=`echo $gtline | cut -d" " -f5`
     jx=`echo $gtline | cut -d" " -f6`
     kx=`echo $gtline | cut -d" " -f7`
     io=`echo $gtline | cut -d" " -f8`
     jo=`echo $gtline | cut -d" " -f9`
     ij=`echo $gtline | cut -d" " -f10`
     export gridno=`echo $gtline | cut -d" " -f11`
     idmpnew=$ix$idmp
     jdmpnew=$jx$jdmp
     iorgnew=$io$iorg
     jorgnew=$jo$jorg

     # create new infile
     cp $infile_orig infile.temp
     sed -e "s/$ioline/$iorgnew/" \
         -e "s/$joline/$jorgnew/" \
         -e "s/$ixline/$idmpnew/" \
         -e "s/$jxline/$jdmpnew/" \
          infile.temp   | \
     sed -n "/ThisLineShouldNotExist/!p" > infile.$gridid
     rm -f infile.temp
     infile=infile.$gridid

     let stoppoint=outfilesize-4
     piece=`echo $outfile_orig | cut -c1-$stoppoint`
     outfilesd=$piece.$gridid.grb

     outfile=$outfilesd

     $USHofs/ofs_gribit.sh
     export err=$?; err_chk
     echo ' ' >> $pgmout
     if [ -s fort.51 ] ; then mv fort.51 $outfile ;fi

     if [ -s $outfile ]
     then
       procstatus=0
       cat latlon.$gridid.grb >> $outfile
     else
       procstatus=1
     fi
     if [ $procstatus = 0 ]
     then
        if [ $SENDCOM = YES ]
        then
          # Copy the grib file to /com:
          cp $outfile $COMOUT/.
          if [ $SENDDBN = YES ] ; then
           $DBNROOT/bin/dbn_alert MODEL OFSATL_GRB $job \
             $COMOUT/$outfile
          fi
        fi
     fi

  fi
done<$PARMofs/${RUN}_${modID}.application_table


echo "*** Finished script $0"
