#!/bin/ksh
#
#   Job to run the land surface model driven by near-surface meteorological forcing
#   Emanuel Dutra, November 2017 ( adapted from CY43R1)
 

set -eux

##==================================================
##  2. function to create input namelist 
function create_input_namelist {

cat > input << EOF
&NAMCT01S
  NSTART=$NSTART           ! first timestep of model 0 
  NSTOP=$NSTOP             ! last timestep of model 17520
  NFRPOS=$NFRPOS           ! frequency of post-processing events (time-steps)
  NFRRES=0                 ! frequency of writing intermediate restart files (time-steps)
  LNF=$LNF                 ! .T. = start, .F. = restart
  NCYCLE=1                 ! number of the experiment
  CNMEXP="${FEXP}"       ! name of the experiment
  /
  &NAMDYN1S
  TSTEP=$OSMTSTEP          !  TSTEP   : length of the timestep in seconds
  NACCTYPE=2               ! =0  Forcing fluxes assument centered on timestamp (linear interp.)
                           ! =1  forward accumulation (starting at timestamp)
                           ! =2  backward accumulation (ending at timestamp)
  LSWINT=.TRUE.            ! SWdown solar angle interpolation if true 
  LPREINT=.FALSE.          ! precipitation interpolation if true
  LFLXINT=.FALSE.          ! SWdown/LWdown linear interpolation if true 
  /
  &NAMDIM
  NLAT=$NLAT               ! number of latitudes
  NLON=$NLON               ! number of longitudes
  NDFORC=$NDFORC           ! namelist forcing dimension
  NSLAB=0                  ! 2D, NSLAB = nr of latitude lines
  NPROMA=240              ! working dimension for grid-point computations
  /
  &NAMRIP
  NINDAT=${NINDAT}         ! run initial date in the form YYYYMMDD 
  NSSSSS=0                 ! initial time in seconds (e.g. for 12h, 43200)
  /
  &NAM1S
  CFFORC='netcdf'          ! CHARACTER: IDENTIFIES THE FORCING DATA SET
  CFOUT='netcdf'           ! CHARACTER: IDENTIFIES THE OUTPUT DATA SET
  CFSURF='netcdf'          ! CHARACTER: IDENTIFIES THE SURFACE CLIMATOLOGY DATA SET 
  CFINIT='netcdf'          ! CHARACTER: IDENTIFIES THE INITIALIZATION DATA SET
  CMODID='EC-EARTH'         ! CHARACTER: MODEL IDENTIFICATION
  CVERID='EC-EARTH'            ! CHARACTER: VERSION IDENTIFICATION 
  LACCUMW=.TRUE.           ! LOGICAL : WRITE OUT ACCUMULATED FLUXES (DEFAULT=TRUE)
  LRESET=.TRUE.            ! LOGICAL : RESET ACCUMULATION EVERY WRITE OUT TIME STEP
  NACCUR=1                 ! INTEGER : OUTPUT CDF ACCURACY: 1=SINGLE PREC, 2=DOUBLE PREC
  NDIMCDF=${NDIMCDF}       ! INTEGER : NR OF GRID DIMENSIONS
  NDLEVEL=${NDLEVEL}       ! INTEGER : Level of netcdf4 compression 0-9: 0== no compression -faster output
  NCDFTYPE=${NCDFTYPE}     ! type of netcdf output
  LNCSNC=.FALSE.           !  if true sync netcdf output every writting step (slows down run)
  LWRGG=$LPROD             ! logical, wrtie o_gg  - instantaneus prognostics 
  LWRCLM=$LPROD            ! logical, write o_fix - fix soil properties 
  LWRGGD=$LPROD            ! logical, write o_ggd - mean prognostic evolution
  LWREFL=$LPROD            ! logical, write o_efl - surface energy balance 
  LWRWAT=$LPROD            ! logical, write o_wat - water balance
  LWRD2M=$LPROD            ! logical, write o_d2m - 2 meters diagnostics 
  LWRSUS=$LPROD            ! logical, write o_sus - surface state variables (vegT,albedo, etc..)
  LWREVA=$LPROD            ! logical, write o_eva - evaporation components 
  LWRCLD=$LPROD            ! logical, write o_cld - cold processes variables 
  LWRCO2=$LPROD            ! logical, write o_co2 - cO2 fluxes 
  LWRBIO=.FALSE.           ! logical, write o_bio - biomass 
  LWRVEG=.FALSE.           ! logical, write o_veg - vegetation 2D high/low veg 
  LWRVTY=$LPROD            ! logical, write o_vty - vegetation 2D high/low veg biomass
  LWRTIL=.FALSE.           ! logical, write o_til - tiles 2D (tile) state
  LWRLKE=.FALSE.           ! logical, write o_lke - lake variables
  LSEMISS=.FALSE.          ! LOGICAL : EMISSIVITY SET TO CONSTANT VALUE REMISS
  LDBGS1=.FALSE.           ! LOGICAL : PRINT DEBUG INFO, EG FORCING DATA (DEFAULT=FALSE)
  IDBGS1=2                 ! Debug level : output printing
  LREADDAY=${LREADDAY}          ! Logical: read daily chuncks  
  /
  &NAMFORC
  ZPHISTA=${ZPHISTA}      ! REFERENCE LEVEL (FOR T, Q) last model level ERAI
  ZUV=${ZUV}          ! REFERENCE LEVEL FOR WIND   last model level ERAI
  ZDTFORC=$ZDTFORC         ! FORCING TIME STEP     3h forcing from ERAI 
  IFYYYY=$IFYYYY           ! REFERENCE YEAR
  IFMM=$IFMM               ! REFERENCE MONTH
  IFDD=$IFDD               ! REFERENCE DAY
  IFTIM=$IFTIM             ! REFERENCE TIME (HHMM)
  INSTFC=0                 ! NUMBER OF TIME STEPS TO BE READ (0 = ALL)
  NDIMFORC=${NDIMCDF}      ! NUMBER OF GRID DIMENSIONS in FORCING
  LOADIAB=.FALSE.          ! FLAG FOR APPLYING ADIABATIC HEIGHT CORRECTION
  CFORCV="$CFORCV"
  CFORCU="$CFORCU"
  CFORCT="Tair.nc"
  CFORCQ="Qair.nc"
  CFORCP="PSurf.nc"
  CFORCRAIN="Rainf.nc"
  CFORCSNOW="Snowf.nc"
  CFORCSW="SWdown.nc"
  CFORCLW="LWdown.nc"
  /
  &NAMPHY
  LEVGEN=$LEVGEN               ! LOGICAL : TURN THE VAN GENUCHTEN HYDROLOGY ON
  LESSRO=$LESSRO                ! LOGICAL : TURN THE SUB-GRID SURFACE RUNOFF ON
  LEFLAKE=.FALSE.              ! LOGICAL : TURN THE FLAKE ON
  LESN09=$LESN09               ! LOGICAL : TURN THE NEW SNOW PARAMETERIZATION ON 
  LEINTWIND=.T.
  LECLIM10D=.F.            ! LOGICAL : TURN usage of 10-day Climatology for Alb and LAI
  LE4ALB=$LE4ALB
  LELAIV=$LELAIV
  /
  &NAMPHYOFF
  LRDALB=$LRDALB
  N_COMPUTE_EFF_VEG_FRACTION=${N_COMPUTE_EFF_VEG_FRACTION}
  /
EOF

}

. config.ksh 

##=================================================
## 1. DEFAULT
RCYCLE=1 
NCYCLE=1

if [[ $DCHUNK == "MON" ]] ; then
  PastCycle=$( date -d "${YMD} - 1 month" "+%Y%m%d" )
  NDAYS=$( date -d "${YMD} + 1 month - 1 day " "+%d" )
elif [[ $DCHUNK == "DAY" ]] ; then
  PastCycle=$( date -d "${YMD} - 1 day" "+%Y%m%d" )
  NDAYS=1
else
  echo "Not coded"
  exit -1 
fi
RESDIR=${DATA}/outdata/${PastCycle} #location of restart file


##=================================================
## 1. run setup
NFRPOS=$(( $(( ${FREQ_PP_OSM} ))/$OSMTSTEP ))  # output frequency in steps 
NSTEPSDAY=$(( 86400/$OSMTSTEP ))                    # number of timesteps per day


## THESE are HARDCODED for NOW !!! 
IFTIM=0000                                          # REFERENCE TIME (HHMM) of forcing
NDLEVEL=0    # no delfation by default to speed up model run : some deflation can be applied latter in the pp/clean tasks  

## check and create RUNDIR
if [ -d $RUNDIR ] ; then rm -rf $RUNDIR ; fi
mkdir -p $RUNDIR
## go to RUNDIR
cd $RUNDIR

## link forcing files to RUNDIR location
ln -s -f ${DATADIR}/*.nc .

## LOGICAL DEFAULTS
LEVGEN=${LEVGEN:-true}
LESSRO=${LESSRO:-true}
LESN09=${LESN09:-true}
LRDALB=${LRDALB:-false}
N_COMPUTE_EFF_VEG_FRACTION=${N_COMPUTE_EFF_VEG_FRACTION:-1}
LE4ALB=${LE4ALB:-true}
LELAIV=${LELAIV:-true}
LREADDAY=${LREADDAY:-true}

IFYYYY=$(echo $YMD | cut -c1-4)
IFMM=$(echo $YMD | cut -c5-6)
IFDD=$(echo $YMD | cut -c7-8)

if [[ $YMD = $DSTART ]]; then # first month of run
  if [[ $RCYCLE = 1  ]]; then # spin up run - get init and clim files
    ln -s $FIXDIR/surfclim surfclim
    ln -s $FIXDIR/soilinit soilinit
    ln -sf soilinit restartin.nc
  else
    echo "need to prepare this option"
    exit -1
  fi
  NSTART=0
  LNF=.TRUE.

else
  if [[ -r ${RESDIR}/restartout.nc ]]; then 
    cp ${RESDIR}/restartout.nc restartin.nc
  else
    echo "Cannot find restart file!"
    exit -1 
  fi
  LNF=.FALSE.
  NSTART=$( ncdump  -v timestp restartin.nc | grep "timestp =" | awk '{print $3}' )
fi
NINDAT=${DSTART}

# Wrting output 
if [ $RCYCLE -lt $NCYCLE  ]; then
  LPROD=.FALSE.  # on spinup do not write ouptut 
else 
  LPROD=.TRUE.  # write output
fi 

t2=$( cdo -s -infov -selvar,LWdown -seltimestep,2 LWdown.nc | tail -1 | awk '{print $3,$4}')
t1=$( cdo -s -infov -selvar,LWdown -seltimestep,1 LWdown.nc | tail -1 | awk '{print $3,$4}')
ZDTFORC=$(( $( date -d "$t2" +%s) - $( date -d "$t1" +%s) ))

## GET INFORMATION FROM NETCDF FILES
NSTOP=$(( $NSTART + $NDAYS*$NSTEPSDAY )) # based on month duration
NDFORC0=$( ncdump -h LWdown.nc  | grep UNLIMITED | awk '{print $6 }' | cut -c2- )
NSTOPF=$(( ($NDFORC0-1)*$ZDTFORC / $OSMTSTEP )) # based on forcing
if [[ $NSTOPF == $(( $NDAYS*$NSTEPSDAY - 1*$ZDTFORC / $OSMTSTEP )) ]]; then
  # special case of last month that does not go until 00 of next month
  NSTOP=$(( $NSTOP - 1*$ZDTFORC / $OSMTSTEP  ))
fi 
NDFORC=$(( $NDFORC0 + 1 ))
if [[ $LREADDAY = true ]]; then
  NDFORC=$(( 86400/ZDTFORC +2 ))
fi 
NLAT=$( ncdump -h restartin.nc | grep "^.y = " |  head -1 | awk '{print $3}' )
NLON=$( ncdump -h restartin.nc | grep "^.x = " |  head -1 | awk '{print $3}' )
if [[ $NLON = "" ]]; then 
  NLAT=$( ncdump -h restartin.nc | grep "^.lat = " |  head -1 | awk '{print $3}' )
  NLON=$( ncdump -h restartin.nc | grep "^.lon = " |  head -1 | awk '{print $3}' )
fi 
NDIMCDF=2
if [[ $NLAT = "" ]]; then 
  NDIMCDF=1
  NLAT=0
fi

if [[ -r Wind.nc ]]; then 
  CFORCV="forcing"
  CFORCU="Wind.nc"
else
  CFORCV="Wind_N.nc"
  CFORCU="Wind_E.nc"
fi

if [[ $FTYPE == "SFC" ]]; then
  ZPHISTA=2.
  ZUV=10.
elif [[ $FTYPE == "ML" ]]; then
  ZPHISTA=10.
  ZUV=10.
fi

create_input_namelist

##=========================================================

ls ${DATADIR}/*

cp $OSMBIN/master1s.exe .

echo "Run" $YMD
abort=no
./master1s.exe 1>osm.log 2>osm.err || abort=yes
set +e 
cat osm.log
cat osm.err 
set -e
[[ $abort = yes ]]  &&  exit 1

pwd
echo "Output" $YMD
ls -ltarh *

exit 0 
