#####################################################################
echo "-----------------------------------------------------"
echo " exgefs_nceppost_master.sh.sms" 
echo " based on exglobal_post.sh.sms" 
echo " Apr 99 - Michaud - Generated to post global forecast"
echo " Mar 03 - Zhu - Add post for 0.5x0.5 degree"
echo " Jul 05 - Wobus - 6-hour breeding, ensemble only"
echo " Jul 07 - Wobus - nceppost creates master files"
echo " Jul 10 - Wobus - create additional anl log file"
echo " Jun 11 - Wobus - move master post files into /com"
echo "-----------------------------------------------------"
#####################################################################

set -x

cd $DATA

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

export MP_LABELIO=YES
#poe hostname

if [[ "$cycsuffix" = "true" ]]; then
  export cfsuffix=".cycfs$cyc_fcst"
else
  export cfsuffix=""
fi
echo cyc=$cyc cyc_fcst=$cyc_fcst
echo cycle=$cycle cycle_fcst=$cycle_fcst
echo fcstlong=$fcstlong
echo cycsuffix=$cycsuffix
echo cfsuffix=$cfsuffix

export WGRIB=${WGRIB:-${EXECUTIL}/wgrib}
export GRBIDX=${GRBIDX:-${EXECUTIL}/grbindex}
export ENSADD=${ENSADD:-$USHGLOBAL/global_ensadd.sh}
export POSTGPSH=${POSTGPSH:-$USHGLOBAL/global_nceppost.sh}

R1=`echo $RUN|cut -c1-3`
R2=`echo $RUN|cut -c4-5`
case $R1 in
  (gec) if (( R2 == 0 )); then 
           (( e1 = 1 ))
	   (( e2 = 2 ))
	fi;;
  (gen) (( e1 = 2 ))
	(( e2 = R2 ));;
  (gep) (( e1 = 3 ))
	(( e2 = R2 ));;
  (*)   (( e1 = 0 ))
	(( e2 = 0 ))
	echo unrecognized RUN=$RUN R1=$R1 R2=$R2 ;;
esac

############################################################
#  Define Variables:
#  -----------------
#  SHOUR        is the starting forecast hour. normally 0 except for restarts.
#  FHOUR        is the ending forecast hour.
#  FHINC        is the increment hour for each forecast steps.
#  FH           is the current forecast hour.
#  SLEEP_TIME   is the number of seconds to sleep before exiting with error.
#  SLEEP_INT    is the number of seconds to sleep between restrt file checks.
#  restart_file is the name of the file to key off of to kick off post.
############################################################

if (( SHOUR == 0 )); then
  ############################################################
  # Post Analysis Files before starting the Forecast Post
  ############################################################
  SLEEP_LOOP_MAX=`expr $SLEEP_TIME / $SLEEP_INT`

  export pgm="postcheck"
  ic=0
  while [ $ic -le $SLEEP_LOOP_MAX ]
  do
    if test -f $COMIN/$cyc/init/${RUN}.t${cyc}z.sanl$cfsuffix
    then
      break
    else
      ic=`expr $ic + 1`
      sleep $SLEEP_INT
    fi
    ###############################
    # If we reach this point assume
    # fcst job never reached restart 
    # period and error exit
    ###############################
    if [ $ic -eq $SLEEP_LOOP_MAX ]
    then
    export err=9
    err_chk
    fi
  done

  if test -f $COMIN/$cyc/init/${RUN}.t${cyc}z.sanl$cfsuffix
  then

    # add new environmental variables for running new ncep post
    # Validation date

     export VDATE=${PDY}${cyc}

    # set outtyp to 1 because we need to run chgres in the post before model start running chgres
    # otherwise set to 0, then chgres will not be executed in global_nceppost.sh

    export OUTTYP=1
    # to generate both types of sigma files

    export OUTTYP=0
    export OUTTYP=1

    # specify output file name from chgres which is input file name to nceppost
    # if model already runs gfs io, make sure GFSOUT is linked to the gfsio file
    # new imported variable for global_nceppost.sh

    export GFSOUT=${RUN}.${cycle}.gfsioanl$cfsuffix

    # specify smaller control file for GDAS because GDAS does not
    # produce flux file, the default will be /nwprod/parm/gfs_master_fhh.parm

    export CTLFILE=$PARMgefs/gefs_master_f00.parm
    cat $CTLFILE

    rm -rf sigfile.anl$cfsuffix
    ln -s $COMIN/$cyc/init/${RUN}.t${cyc}z.sanl$cfsuffix sigfile.anl$cfsuffix

    ####################################
    # Create Master Post File 
    ####################################
    export SIGINP=sigfile.anl$cfsuffix
    export FLXINP=/dev/null
    export FLXIOUT=/dev/null
    rm -rf pgbfout pgbifout
    ln -s $COMOUT/$cyc/master/$RUN.$cycle.master.grbanl$cfsuffix pgbfout
    ln -s $COMOUT/$cyc/master/$RUN.$cycle.master.grbianl$cfsuffix pgbifout
    export PGBOUT=pgbfout
    export PGIOUT=pgbifout
    export IGEN=$IGEN_ANL

  # specify fhr even for analysis because postgp uses it
    export fhr=00
     
  # run nceppost
    export pgm="$POSTGPSH"
    $POSTGPSH
    rc=$?
    if (( rc == 0 )); then
      echo pgm=$pgm completed successfully
    else
      export err=$rc
      err_chk
    fi

  # 20100730 create a separate log file for the analysis for use by prdgen job
    if test $SENDCOM = "YES"
    then
      if (( fhr < 100 ))
      then
	 pad="0"
      else
	 pad=""
      fi
      echo
      ls -al $PGBOUT $PGBIOUT
      echo
      echo "$PDY$cyc$pad$fhr" > $COMOUT/$cyc/misc/${RUN}.t${cyc}z.master.control.anl$cfsuffix
      echo
      ls -al  $COMOUT/$cyc/misc/${RUN}.t${cyc}z.master.control.anl$cfsuffix
      cat  $COMOUT/$cyc/misc/${RUN}.t${cyc}z.master.control.anl$cfsuffix
      echo
    fi
  fi
fi

SLEEP_LOOP_MAX=`expr $SLEEP_TIME / $SLEEP_INT`

(( fhr=SHOUR))
if (( fhr < 10 )); then
  fhr=0$fhr
fi
export fhr

############################################################
# Loop Through the Post Forecast Files 
############################################################
while (( fhr <= FHOUR )) 
do

  ###############################
  # Start Looping for the 
  # existence of the restart files
  ###############################
  export pgm="postcheck"
  ic=1

  while [ $ic -le $SLEEP_LOOP_MAX ]
  do
    if test -f $restart_file$fhr$cfsuffix
    then
      break
    else
      ic=`expr $ic + 1`
      sleep $SLEEP_INT
    fi
    ###############################
    # If we reach this point assume
    # fcst job never reached restart 
    # period and error exit
    ###############################
    if [ $ic -eq $SLEEP_LOOP_MAX ]
    then
      export err=9
      err_chk
    fi
  done

  msg="Starting post for fhr=$fhr"
  postmsg "$jlogfile" "$msg"

  ###############################
  # link sigma and flux files
  ###############################
  rm -rf sigfile flxfile
  ln -s $COMIN/$cyc/sfcsig/${RUN}.t${cyc}z.sf$fhr$cfsuffix sigfile.f$fhr$cfsuffix
  ln -s $COMIN/$cyc/sflux/${RUN}.t${cyc}z.sfluxgrbf$fhr$cfsuffix flxfile.f$fhr$cfsuffix

  ###################################3
  # Create Master Post File
  ###################################3
  if (( fhr > 0 ))
  then 
    export IGEN=$IGEN_FCST 
  else 
    export IGEN=$IGEN_ANL
  fi

  # add new environmental variables for running new ncep post
  # Validation date

  export VDATE=`${EXECUTIL}/ndate +${fhr} ${PDY}${cyc}`
  
  # set outtyp to 1 because we need to run chgres in the post before model start running chgres
  # otherwise set to 0, then chgres will not be executed in global_nceppost.sh

  export OUTTYP=1
  # to generate both types of sigma files
  export OUTTYP=0
  export OUTTYP=1
  
  # specify output file name from chgres which is input file name to nceppost
  # if model already runs gfs io, make sure GFSOUT is linked to the gfsio file
  # new imported variable for global_nceppost.sh

  export CTLFILE=$PARMgefs/gefs_master_fhh.parm
  cat $CTLFILE

  export SIGINP=sigfile.f$fhr$cfsuffix

  export FLXINP=flxfile.f$fhr$cfsuffix
  export FLXIOUT=flxifile.f$fhr$cfsuffix
  rm -rf pgbfout pgbifout
  ln -s $COMOUT/$cyc/master/$RUN.$cycle.master.grbf$fhr$cfsuffix pgbfout
  ln -s $COMOUT/$cyc/master/$RUN.$cycle.master.grbif$fhr$cfsuffix pgbifout
  export PGBOUT=pgbfout
  export PGIOUT=pgbifout
  export ANOMCATSH=${USHGLOBAL}/global_anomcat.sh
    
# RLW 20100910 add cleanup to prevent problems with overparm
  echo
  for file in fort.11 fort.51 h5wav prmsl tfile
  do
    ls -al $file
    if [[ -L $file || -f $file ]]; then
      rm -f $file
      echo $file removed from working directory
    else
      echo $file not removed from working directory
    fi
  done
  echo

# run nceppost
  export pgm="$POSTGPSH"
  $POSTGPSH
  rc=$?
  if (( rc == 0 )); then
    echo pgm=$pgm completed successfully
  else
    export err=$rc
    err_chk
  fi

  if test $SENDCOM = "YES"
  then
    if (( fhr < 100 ))
    then
       pad="0"
    else
       pad=""
    fi
    echo
    ls -al $PGBOUT $PGBIOUT
    echo
    echo "$PDY$cyc$pad$fhr" > $COMOUT/$cyc/misc/${RUN}.t${cyc}z.master.control$cfsuffix
    echo
    ls -al  $COMOUT/$cyc/misc/${RUN}.t${cyc}z.master.control$cfsuffix
    cat  $COMOUT/$cyc/misc/${RUN}.t${cyc}z.master.control$cfsuffix
    echo
  fi

# Set event flag to release the SREF_PREP job at 126 hour:
  if [ $fhr -eq 126 ]; then
     $SMSBIN/setev post_126_ready
  fi

  export fhr=`expr $fhr + $FHINC`
  if (( fhr < 10 ))
  then
    export fhr="0$fhr"
  fi
done

cat $pgmout

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

################## END OF SCRIPT #######################
