#!/bin/ksh
set -x

################################################################################
# Script: exngac_post.sh.sms
# Purpose: run NGAC Postprocessor to generate NGAC products
# Auther: Sarah Lu
#
# Revision Log
#    2012-01-16 Sarah Lu,  Initial script 
#    2012-01-19 Sarah Lu,  Modify err_check
#    2012-03-09 Sarah Lu,  Revise file management
################################################################################

#  Set environment.
export MP_LABELIO=yes

POST_USH=${POST_USH:-$USHngac/ngac_post.sh}

##
##  Run NCEP Unified Post
##

tsleep=60      #seconds to sleep before checking again...1 min
msleep=10      #maximum number of times to sleep... 10 min

if [ $WRITE_DOPOST = .false. ]; then

#Run NCEP post
 msg="Run NCEP Post to Generate Post Product"
 postmsg "$jlogfile" "$msg"

 FH=$SHOUR
 while [ $FH -le $FHMAX ]; do
   if [ $FH -lt 10 ]; then FH=0$FH; fi
   $POST_USH $FH 
   nsleep=0
   fileout=$DATA/NGAC3d.GrbF$FH
   until [[ -s $fileout || $((nsleep+=1)) -gt $msleep ]];do sleep $tsleep;done
   if [[ ! -s $fileout ]]; then
     echo "Cannot find $fileout"
     export err=8; err_chk
   fi
   FH=`expr $FH + $FHOUT`
 done

else 
 
 if [ $OPT_LUMP = NO -a $MAPPING = .false. ]; then
  msg="NGAC post output already created in COM_OUT"
  postmsg "$jlogfile" "$msg"

 else

#Move post files to working directory
  msg="Move post files to working directory"
  postmsg "$jlogfile" "$msg"

  FH=$SHOUR
  while [ $FH -le $FHMAX ]; do
   if [ $FH -lt 10 ]; then FH=0$FH; fi
   for FLAG in $DFILES; do
     filein=$COMOUT/${RUN}.${cycle}.a${FLAG}f$FH
     fileout=$DATA/NGAC${FLAG}.GrbF$FH
     mv $filein $fileout
   done
   FH=`expr $FH + $FHOUT`
  done
 fi

fi


##
## Mapped to 1 x 1 deg
##

if [ $MAPPING  = .true. ]; then

#Map post files 
 msg="Map NGAC products from T126 to 1x1 deg"
 postmsg "$jlogfile" "$msg"

 export grid3="0 6 0 0 0 0 0 0 360 181 0 0 90000000 0 48 -90000000 359000000 1000000 1000000 0"
 FH=$SHOUR
 while [ $FH -le $FHMAX ]; do
   if [ $FH -lt 10 ]; then FH=0$FH; fi
   for FLAG in $DFILES; do
     filein=$DATA/NGAC${FLAG}.GrbF$FH
     fileout=$DATA/${RUN}.${cycle}.a${FLAG}f$FH
     if [ $POST_GRIBVERSION = grib1 ]; then
       $copygb -xg3 $filein $fileout
     elif [ $POST_GRIBVERSION = grib2 ]; then
       $copygb2 -g "$grid3" -x  $filein $fileout
     fi
   done
   FH=`expr $FH + $FHOUT`
 done

else

#Rename post files 
 msg="Rename T126 Grb files"
 postmsg "$jlogfile" "$msg"

 FH=$SHOUR
 while [ $FH -le $FHMAX ]; do
   if [ $FH -lt 10 ]; then FH=0$FH; fi
   for FLAG in $DFILES; do
     filein=$DATA/NGAC${FLAG}.GrbF$FH
     fileout=$DATA/${RUN}.${cycle}.a${FLAG}f$FH
     ${NCP:-cp} $filein $fileout
   done
   FH=`expr $FH + $FHOUT`
 done

fi


