#!/bin/ksh
####################################################
# 
#  This script runs ocean data prep script and then runs MOM4 GODAS
#
#  Original GODAS Author : Dave Behringer
#  Adapted and merged for CFS : S. Moorthi
#
# Here are some parameter settings.
# In this case the analysis segment is set to run for 5 days.
# The ocean model time step defaults to 3600 seconds.
########################################################
set -x

export NDATE=${NDATE:-/nwprod/util/exec/ndate}
export HOMEcfs=${HOMEcfs:-/nw${envir}}
export USHcfs=${USHcfs:-$HOMEcfs/ush}
export EXECcfs=${EXECcfs:-$HOMEcfs/exec}
export PERR=${PERR:-""}
export PARM_GODAS=${PARM_GODAS:-$HOMEcfs/parm/cfs_parm_om/tbl_nml}
export gdas_cyc=${gdas_cyc:-4}
export omres=${omres:-1x1}
export DATA=${DATA:-$(pwd)}
export SENDCOM=${SENDCOM:-NO}
#
export name=${name:-gdsSOLO}                # name of the experiment
export dt_cpld=${dt_cpld:-3600}             # ocean/ice coupling time step (sec)
export dt_ocean=${dt_ocean:-3600}           # ocean time step (sec)

##########################################################################
 export hours=${hours:-0}                   # number of hours to run
 export days=${days:-1}                     # number of days to run
 export months=${months:-0}                 # number of months to run
##########################################################################
#
export ASYM_GODAS=${ASYM_GODAS:-YES}
export GODAS_WNDO=${GODAS_WNDO:-10}
export GODAS_DATA_DELAY=${GODAS_DATA_DELAY:-0}
#
export RUN_ENVIR=${RUN_ENVIR:-prod}
export OPREPSH=${OPREPSH:-$USHcfs/cfs_cdas_oceanprep.sh}
export cWGsh=${cWGsh:-$USHcfs/cfs_cdas_cWG.sh}
export mEN4sh=${mEN4sh:-$USHcfs/cfs_cdas_mEN4.sh}
export mRSTsh=${mRSTsh:-$USHcfs/cfs_cdas_mRST.sh}
export SICEUPDATESH=${SICEUPDATESH:-$USHcfs/cfs_cdas_sice_update.sh} 
export R2TSH=${R2TSH:-$USHcfs/cfs_cdas_R2T.sh}
export rstrt2tm=${rstrt2tm:-$EXECcfs/cfs_cdas_rstrt2tm}
#
export CDATE=${1:-$CDATE}
export CDUMP=${2:-${CDUMP:-gdas}}
export expdir=${3:-$DATA/$name}                  # experiment directory
export RESDIR=${4:-${RESDIR:-$expdir/RESTART}}
export FIX_OCN=${5:-${FIX_OCN:-$HOMEcfs/fix/cfs_fix_om}}
export COMOUT=${COMOUT:-/com/$NET/$envir/cdas.$(echo $CDATE | cut -c1-8)}

mkdir -p $expdir
mkdir -p $RESDIR
#
#     Run ocn_prep script here
#
if [ $RUN_ENVIR != prod ] ; then export DMP_SUF=c ; fi
 mkdir -p $DATA/ocn_prep
 cd $DATA/ocn_prep
 $OPREPSH ocn_prep $LOGNAME $CDATE $CDUMP
 export ocn_dump=$DATA/ocn_prep
 cd $DATA
#
#
# The "savedir" is the location of subdirectories of fixed files,
# output files and restart files. More about them below.
#
 export workdir=${6:-/ptmp/$LOGNAME/${name}_$CDATE}       # work directory
 export GODASEXEC=${GODASEXEC:-$EXECcfs/cfs_cdas_$name}        # executable 
#
# MOM4 uses so-called "tables" to define some procedures and to specify
# data files to be read and various diagnostics to be saved.
# MOM4 also uses namelist in a conventional way to set parameters and options.
# The tables and namelist files are fixed ASCII files.
#
 diagtable=${diagtable:-$PARM_GODAS/diag_table}           # diagnositics table
 datatable=${datatable:-$PARM_GODAS/data_table}           # data override table
 fieldtable=${fieldtable:-$PARM_GODAS/field_table}        # field table
 namelist=${namelist:-$PARM_GODAS/namelist_$omres}        # namelist file
#
# The executable mppnccombine is required to merge netCDF output
# from several processes into a single netCDF file.
#
 mppnccombine=${mppnccombine:-$HOMEcfs/exec/cfs_mppnccombine}

#
# "Obs_dir" is the path to the directory where ocean observations are prepared
# for assimilation. Data for a retrospective analysis are extracted from an
# archive and packaged in ieee files according to the current analysis date.
# Estimates of the local background error variances of temperature and salinity
# are also computed here and saved in ieee files. See cWG.sh and mEN4.sh for
# further details.
#
 Obs_dir=${7:-${Obs_dir:-$workdir/GDS_Obs}}             # path to assimilation observations
#
 export icefile=${8:-${icefile:-$(pwd)/icegrb.$CDUMP.$CDATE}}
 export sstfile=${9:-${sstfile:-$(pwd)/sstgrb.$CDUMP.$CDATE}}

 export DMP_SUF=${DMP_SUF:-""}
 BOMB=0

#----------------------------------------------------------------------------
# setup directory structure
#
  if [ ! -d $workdir/INPUT ]   ; then mkdir  $workdir/INPUT   ; fi
  if [ ! -d $workdir/RESTART ] ; then mkdir  $workdir/RESTART ; fi
  if [ ! -d $workdir/OUT ]     ; then mkdir  $workdir/OUT     ; fi
  if [ ! -d $workdir/INFO ]    ; then mkdir  $workdir/INFO    ; fi
#-----------------------------------------------------------------------------
#
# prep OBS
# --------
# Ocean observations are prepared for assimilation.
# The current analysis date is copied to the prep directories in the
# ascii file "run_date". The temperature (TMP) and salinity (SAL)
# observations are prepared separately.# The background error variances
# for temperature and salinity are computed in the VAR directory.
# See the cWG.sh and mEN4.sh scripts for more details.
#
  mkdir -p $Obs_dir
  mkdir -p $Obs_dir/TMP
  mkdir -p $Obs_dir/SAL
  mkdir -p $Obs_dir/ALT
  mkdir -p $Obs_dir/VAR
#
  export cdumpdir=${cdumpdir:-${dmpdir:-$DMPDIR/dump}}

  if [ $RUN_OPREP = YES ] ; then
    ocn_dump=${ocn_dump:-$cdumpdir}
    cd $Obs_dir/TMP
    $cWGsh 'tmp' $ocn_dump $FIX_OCN ${CDUMP}$DMP_SUF

    cd $Obs_dir/SAL
    $cWGsh 'sal' $ocn_dump $FIX_OCN ${CDUMP}$DMP_SUF

  else
    cd $Obs_dir/TMP
    $cWGsh 'tmp' $cdumpdir $FIX_OCN ${CDUMP}$DMP_SUF

    cd $Obs_dir/SAL
    $cWGsh 'sal' $cdumpdir $FIX_OCN ${CDUMP}$DMP_SUF
  fi


# prep Background VAR

  CDATE1=$($NDATE -$((24/gdas_cyc)) $CDATE)
  export OCNGES=${OCNGES:-$RESDIR/omrestart.$CDUMP.$CDATE1.$CDATE.tar}
  cd $Obs_dir/VAR
  $mEN4sh $expdir $FIX_OCN $expdir $OCNGES

# change to work directory
#
  cd $workdir

  dte=${CDATE:-`cat  $expdir/run_date`}
  yr=`echo "$dte" | cut -c -4`
  mo=`echo "$dte" | cut -c 5-6`
  dy=`echo "$dte" | cut -c 7-8`
  hrs=`echo "$dte" | cut -c 9-10`

# set GODAS_SOLO namelist

  cat > input.nml <<EOF
  &godas_solo_nml
     months = $months
     days   = $days
     date_init = $yr,$mo,$dy,$hrs,0,0
     hours = $hours
     minutes = 0
     seconds = 0
     calendar = 'JULIAN'
     dt_cpld  = $dt_cpld
     dt_ocean = $dt_ocean /
EOF

# Here concatenate the fixed namelist (defined above) with the SOLO namelist.
#
  cat $namelist >> input.nml

# get data sets, input data and executable
# MOM4 uses so-called "tables" to define some procedures and to specify data
# files to be read and various diagnostics to be saved.
# These 3 tables were defined above.
#
  ${NCP:-/bin/cp} $datatable  data_table
  ${NCP:-/bin/cp} $diagtable  diag_table
  ${NCP:-/bin/cp} $fieldtable field_table
#
  cd $workdir/INPUT
#
#  Specify the fixed netCDF files (grid specification, chlorophyll distribution,
#  climatological surface salinity, climatological river runoff, "sponge" data).
#
export  GRIDSPEC=${GRIDSPEC:-$FIX_OCN/grid_spec_$omres.nc}
export  CHLNC=${CHLNC:-$FIX_OCN/chl_$omres.nc}
export  RUNOFFNC=${RUNOFFNC:-$FIX_OCN/runoff_$omres.nc}
export  SNOWNC=${SNOWNC:-$FIX_OCN/SNOW.nc}
export  SSTICECLIM=${SSTICECLIM:-$FIX_OCN/sst_ice_clim.nc}
export  SALTSFCRESTORE=${SALTSFCRESTORE:-$FIX_OCN/salt_sfc_restore_$omres.nc}
export  HICE_CLM=${HICE_CLM:-$FIX_OCN/hice_clm_$omres.nc}
#
#  Execute the script that creates daily restore files
#
##
##   gfs.t00z.sstgrb
##
#${NCP:-/bin/cp} $sstfile $workdir/INPUT/

if [ $RUN_ENVIR = prod -o $RUN_ENVIR = devpara ] ; then
  yyyymmdd=$(echo $CDATE | cut -c1-8)
  for cycl in 00 06 12 18 ; do
    sstf=$COMDIR/cdas.$yyyymmdd/cdas1.t${cycl}z.sstgrb
    if [ -s $sstf ] ; then
      xdate=${yyyymmdd}$cycl
      ${NCP:-/bin/cp} $sstf $workdir/INPUT/sstgrb.$CDUMP.$xdate
      if [ $xdate -eq $CDATE ] ; then
        if [ ! -s $sstfile ] ; then ${NCP:-/bin/cp} $sstf $sstfile ; fi
        if [ ! -s $icefile ] ; then ${NCP:-/bin/cp} $COMDIR/cdas.$yyyymmdd/cdas1.t${cycl}z.engicegrb $icefile ; fi
      fi
    fi
  done
else
  ${NCP:-/bin/cp} $cdumpdir/$CDATE/${CDUMP}$DMP_SUF/sstgrb.$CDUMP.$CDATE $workdir/INPUT/
  CDATE0=$(echo $CDATE | cut -c1-8)00
  hinc=$((24/gdas_cyc))
  nn=0
  while [ $nn -lt 4 ] ; do
    xdate=$($NDATE  $((nn*hinc)) $CDATE0)
    ${NCP:-/bin/cp} $cdumpdir/$xdate/${CDUMP}$DMP_SUF/sstgrb.$CDUMP.$xdate $workdir/INPUT/
    nn=$((nn+1))
  done
  if [ ! -s $sstfile ] ; then
    ${NCP:-/bin/cp} $cdumpdir/$CDATE/${CDUMP}$DMP_SUF/sstgrb.$CDUMP.$CDATE $sstfile
  fi
  if [ ! -s $icefile ] ; then
    ${NCP:-/bin/cp} $cdumpdir/$CDATE/${CDUMP}$DMP_SUF/icegrb.$CDUMP.$CDATE $icefile
  fi
fi

$mRSTsh

#
  ln -sf $GRIDSPEC        grid_spec.nc
  ln -sf $CHLNC           chl.nc
  ln -sf $RUNOFFNC        RUNOFF.nc
  ln -sf $SNOWNC          SNOW.nc
  ln -sf $SSTICECLIM      sst_ice_clim.nc
# ln -sf $SALTSFCRESTORE  salt_sfc_restore.nc  # Commented on 02/08/2008
#
#
# Here ieee observation files and ieee background variance files are copied from
# the OBS directories.
#
  ${NCP:-/bin/cp} $Obs_dir/TMP/tmpa.mom .
  ${NCP:-/bin/cp} $Obs_dir/SAL/sala.mom .
  ${NCP:-/bin/cp} $Obs_dir/VAR/tvv.mom  .
  ${NCP:-/bin/cp} $Obs_dir/VAR/svv.mom  .
#
# The RESTART subdirectory contains a tar file of restart files for various
# MOM4 components. Two of the component files are ascii, the rest are netCDF.
# Extract the restart components.
#
  cd $workdir/INPUT  	
# CDATE1=$($NDATE -$((24/gdas_cyc)) $CDATE)
  tar -xvf $OCNGES                                #  This is the restart file
  for newname in $(ls -rt ${CDATE}* | cut -c11-) ; do
   mv ${CDATE}$newname $newname
  done

#############################################################################
# Call utility to create netcdf file for T, S, U and V to calculate increments

  $R2TSH $CDATE $FIX_OCN omges.$CDUMP.
  INC_DIR=${INC_DIR:-$expdir}
  if [ $RUN_ENVIR = dev ]
  then
  # mv omges.$CDUMP.ocn_$CDATE.nc      $INC_DIR/omges.$CDUMP.$CDATE.nc
    mv $CDATE.omges.$CDUMP.OCEAN_TS.nc $INC_DIR/omges_TS.$CDUMP.$CDATE.nc
    mv $CDATE.omges.$CDUMP.OCEAN_UV.nc $INC_DIR/omges_UV.$CDUMP.$CDATE.nc
  else
    mv $CDATE.omges.$CDUMP.OCEAN_TS.nc $COMOUT/${RUN}.t${cyc}z.tsoges.nc
    mv $CDATE.omges.$CDUMP.OCEAN_UV.nc $COMOUT/${RUN}.t${cyc}z.uvoges.nc
  fi
#############################################################################

  cd $workdir
  
  ${NCP:-/bin/cp} $GODASEXEC .
  export PGM=$workdir/$(basename $GODASEXEC)
  export pgm=$PGM

#-------------------------------------------------------------------------------
# run the model

  echo "Begining GODAS-M4 single analysis at $yr-$mo-$dy"

# export MP_SHARED_MEMORY=no

  poe $pgm > fms.out || set BOMB = 1

  if [ $BOMB -ge 1 ]; then
    echo "Job failure."
    exit [ -1 ]
  else
    echo "Job done."
    echo "Begin post processing."
  fi

  dte=`cat end_date`
#
#  Run the sea ice update script in the INPUT directory and move the output 
#  to the RESTART directory
#
  $SICEUPDATESH $CDATE $icefile $workdir/INPUT

rc=$?
if [[ $rc -ne 0 ]];then echo 'ERROR EXIT AFTER SICE';exit 1;fi
#-------------------------------------------------------------------------------
# make a tar restart file 
# Here the various restart components created at the end of the run by the MOM4
#  executable are combined in a tar file tagged with the run end date (dte).
#
  cd RESTART

  tar -xvf $OCNGES                                             # This is the restart file
  cp ocean_temp_salt.res.nc ${CDATE}ocean_temp_salt.res.nc  # replace old with new
  cp $workdir/INPUT/ice_model.rst.nc ${CDATE}ice_model.res.nc
  for newname in $(ls -rt ${CDATE}* | cut -c11-) ; do
    mv ${CDATE}$newname $newname
  done

#############################################################################
# Call utility to create netcdf file for T, S, U and V to calculate increments

  $R2TSH $CDATE $FIX_OCN omanl.$CDUMP.
  INC_DIR=${INC_DIR:-$expdir}
  if [ $RUN_ENVIR = dev ]
  then
    # mv omanl.$CDUMP.ocn_$CDATE.nc      $INC_DIR/omanl.$CDUMP.$CDATE.nc
    mv $CDATE.omanl.$CDUMP.OCEAN_TS.nc $INC_DIR/omanl_TS.$CDUMP.$CDATE.nc
    mv $CDATE.omanl.$CDUMP.OCEAN_UV.nc $INC_DIR/omanl_UV.$CDUMP.$CDATE.nc
  else
    mv $CDATE.omanl.$CDUMP.OCEAN_TS.nc $COMOUT/${RUN}.t${cyc}z.tsoanl.nc
    mv $CDATE.omanl.$CDUMP.OCEAN_UV.nc $COMOUT/${RUN}.t${cyc}z.uvoanl.nc
  fi
#############################################################################

  set -A resfiles `ls *.res *.nc`
  if [ ${#resfiles[*]} -gt 0 ]; then
    cp $workdir/input.nml .
    cp $workdir/*_table .
    tar -cvf $expdir/ocnanl.$CDUMP.$CDATE.tar *.res *.nc *_table input.nml
  fi

  cd $workdir

#-------------------------------------------------------------------------------
# combine netcdf files
# --------------------
# Here time mean ocean state files written by each process are combined
# by mppnccombine. There are separate netCDF files for fields on the tracer
# and velocity grids. The files are tagged with the run end date (dte).
#
# set -A ocnDiag ocean_TS ocean_UV
# n=0
# while [ n -lt ${#ocnDiag[*]} ]; do
#   echo "  ${ocnDiag[$n]}"
#   set -A file_list `ls -1 ${ocnDiag[$n]}.nc.????`
#   if [ ${#file_list[*]} -gt 0 ]; then
#     diag_name=${ocnDiag[$n]}.$CDUMP.$CDATE.nc
#     if [ ${#file_list[*]} -gt 1 ]; then
#       $mppnccombine $diag_name ${file_list[*]}
#     else
#       mv ${file_list[0]} $diag_name
#     fi
#     ${NCP:-/bin/cp} -p  $diag_name $expdir/$diag_name
#     rm ${ocnDiag[$n]}.nc.????
#   fi
#   ((n=$n+1))
# done
#
#------------------------------------------------------------------------------
# move output to OUT directory
# The ascii file end_date, generated by the MOM4 executable, becomes the
# run_date file for the next run.
#
  cp end_date $expdir/run_date
  cp end_date OUT/run_date
#
#-------------------------------------------------------------------------------

# return to experiment directory

 cd $expdir

#if [ $SENDCOM = YES -a $RUN_ENVIR = prod ] ; then
if [ $SENDCOM = YES ] ; then
  cp ocnanl.$CDUMP.$CDATE.tar $COMOUT/${RUN}.t${cyc}z.ocnanl.tar
  cp ocnanl.$CDUMP.$CDATE.tar $GESdir/${RUN}.t${cyc}z.ocnanl.tar
fi

#-------------------------------------------------------------------------------

