
# This script performs an oi-based quality control on all data
#
# It is normally executed by the script prepobs_makeprepbufr.sh
#  but can also be executed from a checkout parent script
# --------------------------------------------------------------

set -aux

qid=$$

# Positional parameters passed in:
#   1 - path to COPY OF input prepbufr file --> becomes output prepbufr
#       file upon successful completion of this script (note that input
#       prepbufr file is NOT saved by this script)
#   2 - ncep production date (YYYYMMDDHH)

# Imported variables that must be passed in:
#   DATA - path to working directory
#   OIQCT - path to observation error table file
#   OIQCX - path to PREPOBS_OIQCBUFR program executable

# Imported variables that can be passed in:
#   jlogfile - string indicating path to joblog file (skipped over by this
#              script if not passed in)
#   pgmout   - string indicating path to for standard output file (skipped
#              over by this script if not passed in)

cd $DATA
PRPI=$1
if [ ! -s $PRPI ] ; then exit 1;fi
CDATE10=$2

rm $PRPI.oiqcbufr
rm tosslist

pgm=`basename  $OIQCX`
if [ -s prep_step ]; then
   . prep_step
else
   [ -f errfile ] && rm errfile
   export XLFUNITS=0
   unset `env | grep XLFUNIT | awk -F= '{print $1}'`

   set +u
   if [ -z "$XLFRTEOPTS" ]; then
     export XLFRTEOPTS="unit_vars=yes"
   else
     export XLFRTEOPTS="${XLFRTEOPTS}:unit_vars=yes"
   fi
   set -u

fi

export XLSMPOPTS=parthds=2:usrthds=2:stack=64000000

echo "      $CDATE10" > cdate.dat
export XLFUNIT_11=cdate.dat
export XLFUNIT_14=$PRPI
export XLFUNIT_17=$OIQCT
export XLFUNIT_18=obprt_ipoint.wrk
export XLFUNIT_20=tolls.wrk
export XLFUNIT_61=toss.sfc_z
export XLFUNIT_62=toss.temp_wind
export XLFUNIT_63=toss.sat_temp
export XLFUNIT_64=toss.ssmi_wind
export XLFUNIT_65=tosslist
export XLFUNIT_70=$PRPI.oiqcbufr
export XLFUNIT_81=obogram.out
export XLFUNIT_82=obogram.bin
TIMEIT=""
[ -s $DATA/timex ] && TIMEIT=$DATA/timex
$TIMEIT $OIQCX > outout 2> errfile
err=$?
###cat errfile
cat errfile >> outout
cat outout >> oiqcbufr.out
cp outout obcnt.out
set +u
[ -n "$pgmout" ]  &&  cat outout >> $pgmout
set -u
rm outout
set +x
echo
echo 'The foreground exit status for PREPOBS_OIQCBUFR is ' $err
echo
set -x
if [ "$err" -eq '4' ]; then
msg="WRNG: SOME OBS NOT QC'd BY PGM PREPOBS_OIQCBUFR - # OF OBS > LIMIT \
--> non-fatal"
   set +x
   echo
   echo "$msg"
   echo
   set -x
   set +u
   [ -n "$jlogfile" ] && postmsg "$jlogfile" "$msg"
   set -u
   err=0
fi
if [ -s err_chk ]; then
   err_chk
else
   if test "$err" -gt '0'
   then
##### kill -9 ${qid}
      exit 555
   fi
fi

if [ "$err" -gt '0' ]; then
   exit 9
else
   mv $PRPI.oiqcbufr $PRPI
fi

exit 0
