#!/bin/sh
################################################################################
# Script: exngac_prep.sh.sms
# Purpose: run NGAC Preprocessor to prepare NGAC initial conditions
# Auther: Sarah Lu
# Revision Log:   
# 2011-12-10 Sarah Lu,  Initial script 
# 2012-01-13 Sarah Lu,  Add cold_start option
# 2012-01-19 Sarah Lu,  Modify err_check
################################################################################

##  Set environment.
export MP_BINDPROC=${MP_BINDPROC:-yes}
export MEMORY_AFFINIY=${MEMORY_AFFINIY:-MCM}
export MP_SYNC_QP=${MP_SYNC_QP:-yes}
export MP_SHARED_MEMORY=${MP_SHARED_MEMORY:-"NO"}
export MP_COREFILE_FORMAT=${MP_COREFILE_FORMAT:-"lite"}
export VERBOSE=${VERBOSE:-"NO"}
if [[ "$VERBOSE" = "YES" ]]
then
   echo $(date) EXECUTING $0 $* >&2
   set -x
fi

if [ $COLD_START = YES ] ; then

## Run chgres on sfcanl and siganl

 msg="This is a cold-start run"
 postmsg "$jlogfile" "$msg"
 export SIGINP=$SIG_GDAS
 export SFCINP=$SFC_GDAS
 export GFSOUT=$GRDI
 export SFNOUT=$SFCI
 $CHGRESSH

else

 msg="This is a warm-start run"
 postmsg "$jlogfile" "$msg"
 export SIGX=$DATA/sig_nemsio
 export SFCX=$DATA/sfc_nemsio

 if [ $DO_REPLAY = YES ] ; then

   msg="Replay is on -- ingest met analysis"
   postmsg "$jlogfile" "$msg"

## Run chgres on sfcanl
   msg="Run chgres on sfcanl"
   postmsg "$jlogfile" "$msg"
   export SIGINP=
   export SFCINP=$SFC_GDAS
   export GFSOUT=
   export SFNOUT=$SFCX
   $CHGRESSH

## Run replay on siganl and sig_guess
   msg="Run replay on siganl and sig_guess"
   postmsg "$jlogfile" "$msg"
   export SIGFST=$SIG_NGAC
   export SIGANL=$SIG_GDAS
   $REPLAYEXEC $SIGFST $SIGANL $SIGX
   export err=$?; err_chk

 else

   msg="Replay is off -- no met analysis ingest"
   postmsg "$jlogfile" "$msg"
   ${NCP:-cp} $SIG_NGAC $SIGX
   ${NCP:-cp} $SFC_NGAC $SFCX
 fi

## Run chgfhr on sfcx and sigx
 iy=`echo $CDATE | cut -c1-4`
 im=`echo $CDATE | cut -c5-6`
 id=`echo $CDATE | cut -c7-8`
 ih=`echo $CDATE | cut -c9-10`

cat << EOF > $DATA/inlist
 &YMD
  yy=$iy,mm=$im,dd=$id,hh=$ih,
/
EOF

 msg="Run chgfhr to reset forecast hour for sig file"
 postmsg "$jlogfile" "$msg"
 ${NCP:-cp} $SIGX $DATA/in_file
 $CHGFHREXEC < $DATA/inlist > $DATA/chgfhr_sig.$CDATE.out
 export err=$?; err_chk
 mv $DATA/out_file $GRDI

 msg="Run chgfhr to reset forecast hour for sfc file"
 postmsg "$jlogfile" "$msg"
 ${NCP:-cp} $SFCX $DATA/in_file
 $CHGFHREXEC < $DATA/inlist > $DATA/chgfhr_sfc.$CDATE.out
 export err=$?; err_chk
 mv $DATA/out_file $SFCI

fi

################################################################
# Copy ICs from GESdir to COMOUT
################################################################
msg="Copy NGAC ICs from GESdir to COMOUT"
postmsg "$jlogfile" "$msg"

if [[ "$SENDCOM" = "YES" ]]
then
   ${NCP:-cp}  $GRDI $COMOUT/${RUN}.${cycle}.gfsanl
   ${NCP:-cp}  $SFCI $COMOUT/${RUN}.${cycle}.sfcanl
fi
