#!/bin/ksh
# Kornshell Script to run E2OBS offline integrations and preparation for offline analysis cycle
# Provider ECMWF
# Script setup---------------------------------------------------------------------------------
#set -x
data_label=E2OBS                     #project label
#Domain latmin latmax lonmin lonmax
echo 23 52 -127 -65 >latlon_domain   #domain corresponding to CONUS
echo 40 52 -7 13    >latlon_domain   #domain corresponding to AROME-France
echo 25 75 -11 62 >latlon_domain  #domain corresponding to EuroMediterranean region

startdate=20120101
enddate=20120101
# End setup---------------------------------------------
dateloop=$startdate
date_label=$startdate"_to_"$enddate
yyyymmend=`echo $enddate | cut -c1-6`
latindex=`awk '{print int((90+$1)*2+1)","int((90+$2)*2+1)}' latlon_domain`
lonindex=`awk '{print int((180+$3)*2+1)","int((180+$4)*2+1)}' latlon_domain`
echo $latindex $lonindex
exptype='ol'
preczero='off'
#preczero='on'

#Linking forcing
rm -rf forcing
#ln -s E2OBS_20120101_to_20121231.nc forcing
ln -s E2OBS_20120101_to_20120131.nc forcing
if [[ $preczero == 'on' ]] ; then
#Linking perturbed forcing
  rm -rf forcing
  cp E2OBS_20120101_to_20121231.nc E2OBS_20120101_to_20121231_preczero.nc 
  ncflint -vRainf,Snowf -w0,0 E2OBS_20120101_to_20121231.nc E2OBS_20120101_to_20121231.nc -o norain.nc
  ncks -A norain.nc E2OBS_20120101_to_20121231_norain.nc 
  ln -s E2OBS_20120101_to_20121231_norain.nc forcing
fi

# Starting integration step (0 for the first cycle
stepstart=0
daycycle=1
step=`expr $daycycle \* 48`

# Loop on dates
while [ $dateloop -le $enddate ] ; do
        stepend=`expr $stepstart + $step`
	year=`echo $dateloop | cut -c1-4`
	month=`echo $dateloop | cut -c5-6`
	day=`echo $dateloop | cut -c7-8`
        if [[ $stepstart -eq 0 ]] ; then 
		LNF=.T.
		rm -rf surfclim soilinit
		ln -s surfinit_E2OBS.nc soilinit
		ln -s surfclim_E2OBS.nc surfclim
	else 
		LNF=.F. 
		rm -rf surfclim soilinit
                ln -s restartin.nc soilinit
                ln -s restartin.nc surfclim
	fi

# Generates the namelist
cat <<EOF >input
&NAMCT01S
  NSTART=$stepstart        ! first timestep of model 0 
  NSTOP=$stepend           ! last timestep of model 17520
  NFRPOS=48                ! frequency of post-processing events (time-steps)
  NFRRES=0                 ! frequency of writing intermediate restart files (time-steps)
  LNF=$LNF                 ! .T. = start, .F. = restart
  NCYCLE=2                 ! number of the experiment
  CNMEXP="Test"            ! name of the experiment
  /
  &NAMDYN1S
  TSTEP=1800               !  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=101                 ! number of latitudes
  NLON=147                 ! number of longitudes
  NDFORC=3000              ! namelist forcing dimension
  NSLAB=0                  ! 2D, NSLAB = nr of latitude lines
  /
  &NAMRIP
  NINDAT=$startdate        ! 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='CHTESSELLAKE'    ! CHARACTER: MODEL IDENTIFICATION
  CVERID='e2o'             ! 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=2                ! INTEGER : NR OF GRID DIMENSIONS
  NDLEVEL=0                ! INTEGER : Level of netcdf4 compression 0-9: 0== no compression -faster output
  NCDFTYPE=4               ! type of netcdf output 
  LWRGG=.TRUE.             ! logical, wrtie o_gg  - instantaneus prognostics 
  LWRCLM=.TRUE.            ! logical, write o_fix - fix soil properties 
  LWRGGD=.TRUE.            ! logical, write o_ggd - mean prognostic evolution
  LWREFL=.TRUE.            ! logical, write o_efl - surface energy balance 
  LWRWAT=.TRUE.            ! logical, write o_wat - water balance
  LWRD2M=.TRUE.            ! logical, write o_d2m - 2 meters diagnostics 
  LWRSUS=.TRUE.            ! logical, write o_sus - surface state variables (vegT,albedo, etc..)
  LWREVA=.TRUE.            ! logical, write o_eva - evaporation components 
  LWRCLD=.TRUE.            ! logical, write o_cld - cold processes variables 
  LWRCO2=.FALSE.           ! 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=.FALSE.           ! 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 - not active for now... 
  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 
  /
  &NAMFORC
  ZPHISTA=10.              ! REFERENCE LEVEL (FOR T, Q) last model level ERAI
  ZUV=10.                  ! REFERENCE LEVEL FOR WIND   last model level ERAI
  ZDTFORC=10800            ! FORCING TIME STEP     3h forcing from ERAI 
  IFYYYY=2012              ! REFERENCE YEAR
  IFMM=01                  ! REFERENCE MONTH
  IFDD=01                  ! REFERENCE DAY
  IFTIM=0                  ! REFERENCE TIME (HHMM)
  INSTFC=0                 ! NUMBER OF TIME STEPS TO BE READ (0 = ALL)
  NDIMFORC=2               ! NUMBER OF GRID DIMENSIONS in FORCING
  LOADIAB=.FALSE.          ! FLAG FOR APPLYING ADIABATIC HEIGHT CORRECTION
  CFORCV="forcing"
  CFORCU="forcing"
  CFORCT="forcing"
  CFORCQ="forcing"
  CFORCP="forcing"
  CFORCRAIN="forcing"
  CFORCSNOW="forcing"
  CFORCSW="forcing"
  CFORCLW="forcing"
  /
  &NAMPHY
  LEVGEN=.T.               ! LOGICAL : TURN THE VAN GENUCHTEN HYDROLOGY ON
  LESSRO=.T.               ! LOGICAL : TURN THE SUB-GRID SURFACE RUNOFF ON
  LEFLAKE=.T.              ! LOGICAL : TURN THE FLAKE ON
  LESN09=.T.               ! LOGICAL : TURN THE NEW SNOW PARAMETERIZATION ON 
  LELAIV=.T.               ! LOGICAL : TURN THE LAI SEASONAL ON
  LECTESSEL=.T.            ! LOGICAL : TURN CTESSEL ON
  LEAGS=.F.                ! LOGICAL : TURN AGS EVAPORATION
  RLAIINT=0                ! Coefecient for interactive LAI relaxation with clim (1 fully interactive; 0 fully clim)
  LECLIM10D=.F.            ! LOGICAL : TURN usage of 10-day Climatology for Alb and LAI
  /
  &NAMPHYOFF
  LESKTI5=.FALSE.
  LESKTI8=.FALSE.
  LESOILCOND=.FALSE.
  LEWBSOILFIX=.FALSE.
  LEWBCHECK=.FALSE.
  LEWBCHECKAbort=.FALSE.
  LESNCHECK=.FALSE.
  LESNCHECKAbort=.FALSE.
  LESNWBCON=.FALSE.
  /

EOF
# Run the offline land surface model
        ./osmMASTER
        cp restartout.nc ${exptype}_${dateloop}.nc
        if [[ $exptype == 'ol' ]] ; then
           mv restartout.nc restartin.nc
        else
           echo "here call an analysis script and copy analysed field(s) onto restartin.nc"
           ncflint -vSWE -w0.9,0.1 ${exptype}_${dateloop}.nc ol_${dateloop}.nc -o SWE_${dateloop}.nc
           ncks -A SWE_${dateloop}.nc restartout.nc
           mv restartout.nc restartin.nc
        fi
        stepstart=$stepend
	dateloop=`newdate -D $dateloop +$daycycle`
done
