#!/bin/sh
################################################################################
# This script downscaling g3df* to lower resolution, g3dc*.
#
# Usage: exgfs_post_gocart.sh.sms
# Configuration variables:
#   GRID_IDD
#   in_o
################################################################################
set -x
fhr=$1

cd $DATA/$fhr

/nwprod/util/ush/setup.sh

export NDATE=${NDATE:-/nwprod/util/exec/ndate}
export COPYGB=${COPYGB:-/nwprod/util/exec/copygb}

export GRID_IDD=${GRID_IDD:-3}
export IDRT=${IDRT:-0}
export in_o=${in_o:-3}  ## default is budget from fine to coarse
export COPYGBOPTS="-K-1 -B-1 -g$GRID_IDD -i$in_o -x"

export LOGINP=$COMIN/${RUN}.t${cyc}z.logf${fhr}
export G3DINP=$COMIN/${RUN}.t${cyc}z.g3df${fhr}
export G3DOUT=g3dc${fhr}

# Check the availabity of the G3D files:
icnt=1
while [ $icnt -lt 900 ]
do
  if [ -s $LOGINP ]
  then
    break
  else
    sleep 5
    icnt=$((icnt + 1))
    if [ $icnt -ge 360 ]
    then
      msg="ABORTING after 30 mins of waiting for GFS FCST hours $postjobs."
      err_exit $msg
    fi
  fi
done

# Run copygb to downscale files
$COPYGB $COPYGBOPTS $G3DINP $G3DOUT
export err=$?; err_chk

# Check to make sure the file size if correct
fsize=`ls -l $G3DOUT|awk '{print $5}'`
if [ $fsize -le 20000000 ]
then
    msg="The output file is not complete, need to rerun"
    err_exit $msg
else
    msg="The output file size is big enough, it is ok to clean up the G3D file"
#    echo "$PDY$cyc$fhr" > $COMOUT/${RUN}.t${cyc}z.gocart.control
    rm $G3DINP
fi

if [ $SENDCOM = YES ]
then
  cp $G3DOUT $COMOUT/${RUN}.t${cyc}z.gcgrbf${fhr}
  
  if [ $SENDDBN = YES ]
  then
    $DBNROOT/bin/dbn_alert MODEL GFS_PGB $job $COMOUT/${RUN}.${cycle}.gcgrbf${fhr}
  fi
fi

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