#!/bin/sh
#
# Reads in the 'adjust_pops.out' file.  Then runs the statistical model on the 
# cptp grids in the new sref, and outputs the result to a grid.  gdedit then
# places the grid into the gempak file for display.  DRB.  4/1/2004
#
set -x

thisrun=$1
date=$2
the_run=$3

# Switch to the hourly calenh (calenh4) as that has proven to verify very well.
# Switch to calenh7 as that is now the flagship product (8/25/2005). DRB
field=calenh24
 
if [ "$thisrun" = '00' -o "$thisrun" = '03' -o "$thisrun" = '06' -o "$thisrun" = '09' -o "$thisrun" = '12' -o "$thisrun" = '15' -o "$thisrun" = '18' -o "$thisrun" = '21' ]; then
    #no data for pcpn probs at hr 00 thru hr 21
    echo "Exit now as I can not produce probs at hour f00 thru f21"
    exit 0
fi
 
# Turn run hour from two to three digits, if necessary.
firstnum=`echo $thisrun | cut -c 1-1`
if [ "$firstnum" -eq  '0' ]; then
   newnum=`echo $thisrun | cut -c 2-2`
else
   newnum=$thisrun
fi
testnum=$newnum
if [ $testnum -lt 100 ]; then
   thisrun=0${thisrun}
fi

#cp ${modpath}/combine_pops_24hr.out .
cp ${FIXspc}/spc_combine_pops_24hr.out combine_pops_24hr.out
 
hour=${thisrun}
chour=$hour
model=caltrw12_${the_run}_f${chour}

hour=`echo $hour | cut -c 2-3`
echo "hour= $hour"
hourm12=`expr $hour - 12`
echo "hourm12= $hourm12"
chourm12=0$hourm12
if [ $hourm12 -lt 10 ]; then
    chourm12=00${hourm12}
fi

model12=caltrw12_${the_run}_f${chourm12}

echo "Looking for the file $workdir/${model}"
echo "Looking for the file ${COMIN}/${model12}"

rm -f ./file?.out > /dev/null 2>&1
count=1
while [ $count -lt 180 ]
do
  if [ -s $workdir/$model -a -s ${COMIN}/${model12} ]; then
     echo " "
     echo "Files are ready...move on."
     # sleep a bit, just to make sure the file is complete.
     sleep 2
     break
  else
     echo " "
     echo "Files not all found...${count}"
     let "count=count+1"
     sleep 10
  fi

  #  wait upto 30 minutes for previous files to finish...
  if [ $count -ge 178 ]
  then
        echo "$job: COULD NOT LOCATE: ${COMIN}/${model12}"
  fi
done

#
# Now run the fortran software to read files and calibrate thunder pops...
#
rm -f ./file3.out > /dev/null 2>&1

export pgm=spc_calibrate2_24hr
. prep_step

msg="$job: spc_calibrate2_24hr $the_run f$chour started"
postmsg "$jlogfile" "$msg"

${EXECspc}/spc_calibrate2_24hr $workdir/$model ${COMIN}/${model12} $date $the_run f$chour >>$pgmout 2>errfile
export err=$?;err_chk

# Now use gdedit to put the file into the sref file...
$GEMEXE/gdedit << EOF
 GDEFIL   = ./file3.out
 GDFILE   = ./spcsref_${date}${the_run}f${chour}
 GPACK    =  
 
 r
 
 ex
 
EOF

$GEMEXE/gpend

