#!/bin/sh 
# env vars used:
# ANALHR, datapath datapath2, obs_datapath, HXONLY, DIAGCONV, SAVEHX
# HOMEGLOBAL, charnanal 

echo "starting gsi at `date`"
export cyc=$ANALHR
homedir=$PWD
export CDATE=$analdate

#date

#export PS4='$SECONDS + '
#date
set -xa

# #### 05/05/99 ###############################
# SETUP GFS ANALYSIS PROCESSING VARIABLES
# #############################################

####################################
# obtain unique process id (pid) and make temp directory
####################################
export pid=$$
job='gsitmp'
export DATA=$datapath2/${job}.${pid}
mkdir $DATA
cd $DATA

export cycle=t${cyc}z

####################################
# Specify NET and RUN Name and model
####################################
export NET=$RUN
#export RUN=gdas1
# output diagnostic file for conventional obs.
#export DIAGCONV=.true.
# only do forward operator, exit GSI before minimization.
#export HXONLY=.true.

####################################
# File To Log Msgs
####################################
export jlogfile=/com/logs/para/jlogfile

####################################
# Determine Job Output Name on System
####################################
export outid="LL$job"
export jobid="${outid}.o${pid}"
export pgmout="OUTPUT.${pid}"
export pgmerr=$logdir/errfile

####################################
# SENDSMS  - Flag Events on SMS
# SENDCOM  - Copy Files From TMPDIR to $COMOUT
# SENDDBN  - Issue DBNet Client Calls
# VERBOSE  - Specify Verbose Output in exglobal_fcst.sh.sms
####################################
export SENDSMS=YES
export SENDCOM=YES
export SAVEGES=YES
export SENDDBN=NO
export VERBOSE=YES

####################################
# Specify Execution Areas
####################################
#export EXECGLOBAL=$HOMEGLOBAL/bin
#export FIXGLOBAL=$HOMEGLOBAL/fix
#export USHGLOBAL=$HOMEGLOBAL/ush

export ERRSCRIPT=err_chk
export LOGSCRIPT=startmsg
export FILESTYLE='L'

##############################
# Set up the UTILITIES
##############################
#export utilscript=/nwprod/util/ush
#export utilexec=/nwprod/util/exec

##############################
# Run setup to initialize working directory and utility scripts
##############################
#sh $utilscript/setup.sh

##############################
# Run setpdy and initialize PDY variables
##############################
#sh $utilscript/setpdy.sh
#. PDY

##############################################
# Define COM directories
##############################################
export COMIN=$obs_datapath/${analdate}/gdas
export COMOUT=$datapath2
mkdir -m 775 -p $COMOUT

##############################################
# Define GES directories
##############################################
gespath=$COMIN
export GESdir=$gespath
##mkdir -m 775 -p $GESdir

####################################
# Specify Special Fcst Vars
####################################
#
# Forecast Horizontal Resolution
#
#export JCAP=126
#export JCAP_ges=126
#export JCAP=126
#export JCAP_ges=126 
#
# Forecast Vertical Resolution
#
#export LEVS=64
#export LEVS_ges=64
#
# These are for the T382L64
#
#export LONA=768
#export LATA=384
#export LONB=1152
#export LATB=576
# t254
#export LONA=512
#export LATA=256
#export LONB=768 
#export LATB=384
# t126
#export LONA=256
#export LATA=128
#export LONB=384  
#export LATB=190
#export LSOIL=4
export NLAT=$((${LATA}+2))
#
# Analysis Fix Fields
#
export FNGLAC=${FIXGLOBAL}/global_glacier.2x2.grb
export FNMXIC=${FIXGLOBAL}/global_maxice.2x2.grb
export FNTSFC=${FIXGLOBAL}/cfs_oi2sst1x1monclim19822001.grb
export FNSNOC=${FIXGLOBAL}/global_snoclim.1.875.grb
export FNZORC=${FIXGLOBAL}/global_zorclim.1x1.grb
export FNALBC=${FIXGLOBAL}/global_albedo4.1x1.grb
export FNAISC=${FIXGLOBAL}/cfs_ice1x1monclim19822001.grb
export FNTG3C=${FIXGLOBAL}/global_tg3clim.2.6x1.5.grb
export FNVEGC=${FIXGLOBAL}/global_vegfrac.0.144.decpercent.grb
export FNVETC=${FIXGLOBAL}/global_vegtype.1x1.grb
export FNSOTC=${FIXGLOBAL}/global_soiltype.1x1.grb
export FNSMCC=${FIXGLOBAL}/global_soilmcpc.1x1.grb
export FNOROG=${FIXGLOBAL}/global_orography.t${JCAP}.grb
export FNMASK=${FIXGLOBAL}/global_slmask.t${JCAP}.grb

export BERROR=${FIXGSI}/global_berror.l${LEVS}y${NLAT}.f77

export SATANGL=${FIXGSI}/global_satangbias.txt
export SATINFO=${FIXGSI}/global_satinfo.txt.n19_off.r2008
export RTMSPEC=${FIXGSI}/global_CRTM_SpcCoeff.f77
export RTMTRAN=${FIXGSI}/global_CRTM_TauCoeff.f77
export RTMEMIS=${FIXGSI}/crtm_gfsgsi/EmisCoeff/Big_Endian/EmisCoeff.bin
export RTMAERO=${FIXGSI}/crtm_gfsgsi/AerosolCoeff/Big_Endian/AerosolCoeff.bin
export RTMCLDS=${FIXGSI}/crtm_gfsgsi/CloudCoeff/Big_Endian/CloudCoeff.bin

export CONVINFO=${FIXGSI}/global_convinfo.txt
export OZINFO=${FIXGSI}/global_ozinfo.txt.r2008
export PCPINFO=${FIXGSI}/global_pcpinfo.txt


#
# Analysis Input Fields
#
export PREINP=${RUN}.${cycle}.
export PREINPm1=${RUN}.${cyclem1}.
export FNTSFA=${COMIN}/sstgrb.gdas.$analdate
export FNACNA=${COMIN}/icegrb.gdas.$analdate
export FNSNOA=${COMIN}/snogrb_t382.gdas.$analdate

#export SIGGES=${COMIN}/${PREINP}sgesprep
#export SIGG03=${COMIN}/${PREINP}sgm3prep
#export SIGG09=${COMIN}/${PREINP}sgp3prep

#export PREPQC=${COMIN}/${PREINP}prepbufr
#export B1HRS2=${COMIN}/${PREINP}1bhrs2.tm00.bufr_d
#export B1MSU=${COMIN}/${PREINP}1bmsu.tm00.bufr_d
#export B1HRS3=${COMIN}/${PREINP}1bhrs3.tm00.bufr_d
#export B1AMUA=${COMIN}/${PREINP}1bamua.tm00.bufr_d
#export B1AMUB=${COMIN}/${PREINP}1bamub.tm00.bufr_d
#export B1HRS4=${COMIN}/${PREINP}1bhrs4.tm00.bufr_d
#export B1MHS=${COMIN}/${PREINP}1bmhs.tm00.bufr_d
#export AIRSBF=${COMIN}/${PREINP}airsev.tm00.bufr_d
#export SBUVBF=${COMIN}/${PREINP}osbuv.tm00.bufr_d
#export SMIPCP=${COMIN}/${PREINP}spssmi.tm00.bufr_d
#export TMIPCP=${COMIN}/${PREINP}sptrmm.tm00.bufr_d
#export GPSBF=${COMIN}/${PREINP}gpsro.tm00.bufr_d

############################################################################ 
#
# Check grib date of current snogrb vs that of prev cycle 
#
# if cdate_of_snogrb -le cdate_of_snoprv, i.e. file has not been updated 
#   then set namelist input to CYCLEXEC to use the snow from the guess
#   FNSNOA=" ";CYCLVARS="FSNOL=99999.,FSNOS=99999.,"
#   FNSNOA is the name of the snow depth  analysis file 
#     when not supplied, signals to CYCLEXEC to blend guess and climatology
#     (Note: file must be " ", not "" or the shell syntax for default
#      values X=${X:-default} will reset to default if X="")
#     FSNOL=99999.,FSNOS=99999., sets the blending of guess and climo to
#		use 100% guess
#
####################################
#prev_cdate=$($utilexec/ndate -6 $PDY$cyc)
#snoprv=`$utilscript/getges.sh -q -t snogrb_high -v $prev_cdate`
#if [ `$utilexec/wgrib -4yr ${FNSNOA} 2>/dev/null|grep -i snowc |\
#	  awk -F: '{print $3}'|awk -F= '{print $2}'` -le \
#     `$utilexec/wgrib -4yr $snoprv 2>/dev/null |grep -i snowc  |\
#			awk -F: '{print $3}'|awk -F= '{print $2}'` ] ; then
#	export	FNSNOA=" "
#	export CYCLVARS="FSNOL=99999.,FSNOS=99999.,"
#fi
############################################################################ 
#
# Output File Names
#
export SIGANL=${SIGANL:-$COMOUT/siganl_gsi}
export SFCANL=${SFCANL:-$COMOUT/sfcanl_gsi}
export ABIAS=${ABIAS:-$COMOUT/abias}
export SATANGO=${SATANGO:-$COMOUT/satang}
#export GINCOUT=$COMOUT/${RUN}.${cycle}.gesfile
export GINCOUT=/dev/null
#export PCPSTAT=${COMOUT}/${RUN}.${cycle}.pcpstat
#export RADSTAT=${COMOUT}/${RUN}.${cycle}.radstat
#export GSISTAT=${COMOUT}/${RUN}.${cycle}.gsistat
#export CNVSTAT=${COMOUT}/${RUN}.${cycle}.cnvstat
#export OZNSTAT=${COMOUT}/${RUN}.${cycle}.oznstat
export PCPSTAT=/dev/null
export RADSTAT=/dev/null
export GSISTAT=/dev/null
export CNVSTAT=/dev/null
export OZNSTAT=/dev/null

#
# PDS Grid Designator
#
export IGEN=81

msg="HAS BEGUN on `hostname`"
#postmsg "$jlogfile" "$msg"

####################################
# Check if this is a restart
#
# Define Previous Guess File Names
####################################
#gesenvir=${envir}
#
## $utilscript/getges.sh -t sfcges -r ${JCAP_ges}${LEVS_ges} -v $PDY$cyc \
# -e $gesenvir bges
#err1=$?
## $utilscript/getges.sh -t sfcgm3 -r ${JCAP_ges}${LEVS_ges} -v $PDY$cyc \
# -e $gesenvir sfcf03
##$utilscript/getges.sh -t sfcgp3 -r ${JCAP_ges}${LEVS_ges} -v $PDY$cyc \
# -e $gesenvir sfcf09
##$utilscript/getges.sh -t biascr -r ${JCAP_ges}${LEVS_ges} -v $PDY$cyc \
# -e $gesenvir gbias
##$utilscript/getges.sh -t satang -r ${JCAP_ges}${LEVS_ges} -v $PDY$cyc \
# -e $gesenvir gsatang


#if test "$err1" -eq '0' 
##if [ -s $GBIAS ] && [ -s $GSATANG ] && [ -s $SFCGES ] && [ -s $SFCG03 ] && [ -s $SFCG09 ] && [ -s $SIGGES ] && [ -s $SIGG03 ] && [ -s $SIGG09 ]; 
if [ -s $GBIAS ] && [ -s $GSATANG ] && [ -s $SFCG06a ] && [ -s $SFCG03a ] && [ -s $SFCG09a ] && [ -s $SIGGES ] && [ -s $SIGG03 ] && [ -s $SIGG09 ];
then
   echo "Analysis Starting/Guess Fields Found"
   #postmsg "$jlogfile" "$msg"

else
   echo "Analysis Cannot Start/Guess Fields Not Available"
   exit 1
   #postmsg "$jlogfile" "$msg"
   #export pgm=$job
   #export err=911
   #err_chk
fi

############################
# Make use of updated angle dependent bias file, if it exists.
if [[ -s $GSATANG ]]; then
   export SATANGL=$GSATANG
fi

env

############################
# Added for pmdv hang trace
# -Item T44 Problem on Technical List
############################
#export MP_PMDLOG=yes
#export MP_INFOLEVEL=6
############################

############################
# Added to reduce wall time when running more than one task per node
#export MP_SHARED_MEMORY=YES

#NOTE:  BIND_TASKS=YES requires running 16 tasks/node
#export MP_USE_BULK_XFER=yes
#export BIND_TASKS=YES



#############################################################
# Execute the script
echo "executing run_gsi at `date`"
sh ${homedir}/run_gsi
#############################################################

#export MP_PMDLOG=no
#poe rm /tmp/mplog*

##########
# NOTES: 1) script exglobal_analysis.sh.sms compresses the contents of
#           RADSTAT, PCPSTAT, OZNSTAT, and CNVSTAT.  These stat files
#           files are tarballs of compressed files.
#        2) SFCANL, SIGANL are input to the GFS forecast following the analysis  
#        3) ABIAS, and SATANGO are used in the following analysis cycle
#        4) GINCOUT from the GFS early cycle (GFS) is used as input in the
#           GFS late (GDAS) cycle
#        5) GSISTAT, RADSTAT, PCPSTAT, OZNSTAT, CNVSTAT are diagnostic output
##########

#if test "$SAVEGES" = "YES"
#then
#   cp $SFCANL  $GESdir/${RUN}.${cycle}.sfcanl
#   cp $SIGANL  $GESdir/${RUN}.${cycle}.sanl
#   cp $ABIAS   $GESdir/${RUN}.${cycle}.abias
#   cp $SATANGO $GESdir/${RUN}.${cycle}.satang
#   cp $GINCOUT $GESdir/${RUN}.${cycle}.gesfile
#fi
#if test "$SENDCOM" = "YES"
#then
#   cp $SFCANL  $COMOUT/${RUN}.${cycle}.sfcanl
#   cp $SIGANL  $COMOUT/${RUN}.${cycle}.sanl
#   cp $ABIAS   $COMOUT/${RUN}.${cycle}.abias
#   cp $SATANGO $COMOUT/${RUN}.${cycle}.satang
#   cp $GINCOUT $COMOUT/${RUN}.${cycle}.gesfile
#fi
#
#cat $pgmout
#
#grep resident $DATA/mpi*
#
#echo "`hostname`  --  `date`" > $COMOUT/where_ibm_${RUN}_anal_ran.${cycle}

msg="ENDED NORMALLY."
#postmsg "$jlogfile" "$msg"

##############################
# Remove the Temporary working directory
##############################
cd $homedir
rm -rf $DATA
echo "ending gsi at `date`"