#! /bin/sh
set -x
###############################################################################
# This script is the Analysis exget_sstobs_mods.sh of the HYCOM model. #
# This script is similar to the one in ROFS and get the observational 
# SST data from modsBUFR
#                                                              #
# Remarks :                                                    #
# - For non-fatal errors output is witten to the seas.log file #
# 
# exported vars
#   datatype
#   field
#   cycle
#                                                                             #
###############################################################################

echo "*** Started script $0"

# --------------------------------------------------------------------------- #
# 0.  Preparations
# 0.a Basic modes of operation
echo '                ************************************'
echo '                *** extract sstnvh obs from Analysis ***'
echo '                ************************************'

pastdate=$1
srtdate=$2

#######################################################
# Input Data 
#######################################################
${dumpmb} ${pastdate} ${srtdate} ${datatype}

#######################################################
# Execute Fortran Program
#######################################################

export ext=txt
export latmin=$latobsmin
export latmax=$latobsmax
export lonmin=$lonobsmin
export lonmax=$lonobsmax

ADATE=$pastdate
#enddate=`$NDATE +24 $srtdate$cyc | cut -c1-8`
enddate=`${utilexec}/ndate +\`expr 24 \` ${srtdate}00`                                                                              
enddate=`echo $enddate | cut -c1-8`

while [[ $ADATE < $enddate ]]
do

echo "ADATE is $ADATE"
cat > getsat_mods.in <<EOF
${ADATE}
avhrr.${field}.$ADATE.txt
${lonobsmin}
${lonobsmax}
${latobsmin}
${latobsmax}
EOF

export pgm=ofs_getsat_mods
. prep_step

export XLFRTEOPTS="unit_vars=yes"
export XLFUNIT_21=${datatype}.${ADATE}

startmsg

# run decoder
$EXECofs/ofs_getsat_mods < getsat_mods.in >> $pgmout 2> errfile  
export err=$?; err_chk

cat avhrr.${field}.$ADATE.txt >> tmp.file

#ADATE=`$NDATE +24 $ADATE$cyc | cut -c1-8`
ADATE=`${utilexec}/ndate +\`expr 24 \` ${ADATE}00`                                                                              
ADATE=`echo $ADATE | cut -c1-8`

done

mv tmp.file avhrr.${field}.$srtdate.txt

if [ ! -s avhrr.${field}.$srtdate.txt ]
then
   echo "FATAL ERROR!!! NO avhrr.${field}.$srtdate.txt generated!"
   err=1; err_chk
fi

#######################################################


echo "*** Finished script $0"
