#!/bin/bash
set -evx 
# 
# This script extrapolates horizontally,
# fills up empty seas with climatologies, extrapolate vertically, for GloSea5 restarts. 
#
# History : Virginie Guemas - Initial version                           2012 
#           Virginie Guemas - ORAS4 + vertical extrapolation + 
#                             commenting and clarifying         - March 2014
#           Eleftheria Exarchou - GloSea5                       - January 2015
# 
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#                                Arguments
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
type='glosea5' # 'glorys' / 'metoffice' : if you add another type, you'll have
             # to adapt the list of variables this restart contains below.
             # Look for the variable $type in the script.
fillinrot='TRUE' # Extrapolate or not the rotational rotn / rotb
                  # TRUE increases subtantially the interpolation time 
                  # FALSE has negligible effects ( u, v, t, s are initialized )
restart_in=$1 # Input restart file name without the .nc extension
#meshmaskin='/cfu/autosubmit/con_files/mesh_mask_nemo.nemovar_O1L42_new.nc'
meshmaskin='mask_GS5.nc'
    # Meshmask of the input reanalysis. Example:
    #'/cfu/autosubmit/con_files/mesh_mask_nemo.glorys2v1_O25L75.nc'
confout='ORCA025L75' # output configuration
#vertgridout='/cfu/autosubmit/con_files/mesh_mask_nemo.Ec3.0_O25L75.nc'
vertgridout='mesh_mask_nemo.Ec3.0_O25L75_ClosedSeas.nc'
    # Meshmask of the output restart, i.e. model and grid to be used in
    # climate prediction 
#Ptoextrap='/cfu/pub/scripts/prep_restarts/auxfiles/masks/Tofill_ecearth.v3.0.ORCA1L46.extrap.oras4.nc'
Ptoextrap='Tofill_extrap.nc'
    # Locations of the points where to extrapolate horizontally the restarts after
    # interpolation = 1 in the netcdf file, 0 everywhere else. Locations available
    # for the tmask, umask, vmask and fmask grid. If you don't know about those
    # four variables read about the NEMO documentation about the grid.
    # To obtain the Ptoextrap netcdf file, it is necessary to run once this script
    # without extrapolation and filling of the empty seas and compare the output
    # restart with the output meshmask. To do so, set 0 everywhere in Ptoextrap
    # and use build_Tofill.bash afterwards.
#Ptofillclim='/cfu/pub/scripts/prep_restarts/auxfiles/masks/Tofill_ecearth.v3.0.ORCA1L46.clim.nc'
Ptofillclim='Tofill_clim.nc'
    # Locations of the empty seas that need to be filled up with a climatology after
    # interpolation = 1 in the netcdf file, 0 everywhere else. Locations available
    # for the tmask, umask, vmask and fmask grid. If you don't know about those
    # four variables read about the NEMO documentation about the grid.
    # To obtain the Ptofillclim netcdf file, it is necessary to run once this script
    # without extrapolation and filling of the empty seas and compare the output
    # restart with the output meshmask. To do so, set 0 everywhere in Ptofillclim
    # and use build_Tofill.bash afterwards.
mon=$3 # Month of the restart on 2 digits MM
restart_out=$2 # Output restart file name without the .nc extension
cfutools='/home/eexarchou/git-stuff/cfutools'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

case $type in
  'glorys') 
# List of 3d variables = that need to be vertically interpolated 
   listvarsinterp=( 'en' 'avt' 'avmt' 'avmu' 'avmv' 'dissl' 'ub' 'vb' 'tb' 'sb' 'rotb' 'hdivb' 'un' 'vn' 'tn' 'sn' 'rotn' 'hdivn' 'rhop' )
# List of 2d variables = that only need extrapolation  
   listvarsextrap=( 'gcx' 'gcxb' 'gcxbfs' 'gru' 'grv' 'gsu' 'gsv' 'gtu' 'gtv' 'ssh_m' 'sshb' 'sshn' 'sss_m' 'sst_m' 'ssu_m' 'ssv_m' )
# List of 0d variables = that need to be copied to the output restart
   varscopy='nn_fsbc,rdt,rdttra1'
  ;;
  'oras4')
   listvarsinterp=( 'en' 'ub' 'vb' 'tb' 'sb' 'rotb' 'hdivb' 'un' 'vn' 'tn' 'sn' 'rotn' 'hdivn' )
   listvarsextrap=('alb_ice' 'gcx' 'gcxb' 'sshb' 'sshn' 'u_io' 'v_io' 'sst_io' 'sss_io' ) 
   varscopy='nfice,rdt,rdttra1,ndastp,adatrj'
  ;;
  'glosea5')
   listvarsinterp=( 'tb' )
   listvarsextrap=('gcx' 'gcxb' 'sshb' 'sshn' ) 
   varscopy='rdt,rdttra1,kt,ndastp,adatrj'
  ;;
esac

source ${cfutools}/prep_restarts/library/library.bash

if [[ $fillinrot == 'FALSE' ]] ; then
 cp ${Ptoextrap} Ptoextrap.nc 
 ncks -v fmask Ptoextrap.nc tmp1.nc
 cdo mulc,0 tmp1.nc tmp2.nc
 ncks -A tmp2.nc Ptoextrap.nc
 rm -f tmp1.nc tmp2.nc
 Ptoextrap='Ptoextrap.nc'
fi

# Copy the 0d variables from the input restart to the output restart


if [[ ! -e ${restart_out}.nc ]] ; then
ncks -O -v $varscopy ${restart_in}.nc ${restart_out}.nc
ncks -A -v nav_lon,nav_lat $meshmaskin ${restart_out}.nc
ncks -A -v nav_lev $vertgridout ${restart_out}.nc
fi 

# Fist loop is: Vertical interpolation + horizontal extrapolation at each level + filling empty seas + vertical extrapolation
cdo vertsum -selvar,tmask,vmask,umask,fmask $meshmaskin mask2din.nc
for var in ${listvarsinterp[@]} ; do
  case $var in
   'avmu'|'un'|'ub') mask='umask' ; varlon='glamu' ; varlat='gphiu' ; fill='umask' ;;
   'avmv'|'vn'|'vb') mask='vmask' ; varlon='glamv' ; varlat='gphiv' ; fill='vmask' ;;
   'rotb'|'rotn') mask='fmask' ; varlon='glamf' ; varlat='gphif' ; fill='fmask' ;;
   'avt'|'avmt'|'en'|'dissl'|'hdivb'|'hdivn'|'rhop'|'sn'|'tn'|'sb'|'tb') mask='tmask' ; varlon='glamt' ; varlat='gphit' ;  fill='tmask' ;;
  esac
#  # The vertical interpolation is performed below
#  python ${cfutools}/interpolation/interp_vert.py ${restart_in}.nc $var $meshmaskin e3t_0 mask2din.nc $mask $vertgridout e3t_0 gdept_0 ${var}_${restart_out}_int.nc


  # The function extrap extrapolates horizontally and fill in the empty seas with a climatology
  #extrap ${var}_${restart_out}_int.nc ${var} ${meshmaskin} ${varlon} ${varlat} ${Ptoextrap} ${Ptofillclim} ${fill} ${var}_${restart_out}_int2.nc 3d $cfutools $confout $mon 

  if [ ! -e ${fill}.nc ] ; then
  cdo -setctomiss,0 -selvar,${fill}  $meshmaskin  ${fill}.nc 
  fi 
  cdo  -ifthen ${fill}.nc  -selvar,${var} ${restart_in}.nc  ${var}_${restart_in}.nc
# Modify the missing value to 1e20 
  ncatted -O -a _FillValue,${var},m,f,1e20      ${var}_${restart_in}.nc
  ncatted -O -a  missing_value,${var},m,f,1e20  ${var}_${restart_in}.nc
  extrap ${var}_${restart_in}.nc ${var} ${meshmaskin} ${varlon} ${varlat} ${Ptoextrap} ${Ptofillclim} ${fill} ${var}_${restart_out}_int.nc 3d $cfutools $confout $mon 

  # The vertical extrapolation to empty levels is performed below
# python ${cfutools}/interpolation/vertextrap.py  ${var}_${restart_out}_int2.nc ${var} $vertgridout nav_lev ${var}_${restart_out}_int3.nc
# python ${cfutools}/interpolation/vertextrap.py  ${restart_in}.nc ${var} $vertgridout nav_lev ${var}_${restart_out}_int3.nc

  # Apply the mask
  applymask $vertgridout $mask ${var}_${restart_out}_int.nc $var ${var}_${restart_out}.nc

  # Pasting the output to ${restart_out}.nc
  gathervar ${restart_out}.nc ${var}_${restart_out}.nc
  # for some un known reason (nco bug?) after ncks -A of gathervar, the zaxis gets corrupted, so I reset it. 
  cdo -O  setzaxis,L75   ${restart_out}.nc    ${restart_out}_2.nc  
  mv   ${restart_out}_2.nc  ${restart_out}.nc 
#  rm -f ${var}_${restart_out}.nc ${var}_${restart_out}_int?.nc  
done

##---------------------------------------------------------------------------------
##---------------------------------------------------------------------------------
## Second loop is: horizontal extrapolation at each level + filling empty seas for 2D variables. 
# Horizontal extrapolation and filling empty seas of 2d variables
ncks -O -d lev,0 ${Ptoextrap} Ptoextrap_lev0.nc
ncks -O -d lev,0 ${Ptofillclim} Ptofillclim_lev0.nc
ncks -O -d z,0 $vertgridout mask_lev0.nc
ncks -O -d z,0 $meshmaskin maskin_lev0.nc

for var in ${listvarsextrap[@]} ; do
  case $var in
   'gru'|'gsu'|'gtu'|'ssu_m'|'u_io') varlon='glamu' ; varlat='gphiu' ; fill='umask' ;;
   'grv'|'gsv'|'gtv'|'ssv_m'|'v_io') varlon='glamv' ; varlat='gphiv' ; fill='vmask' ;;
   'gcx'|'gcxb'|'gcxbfs'|'ssh_m'|'sshb'|'sshn'|'sss_m'|'sst_m'|'alb_ice'|'sst_io'|'sss_io') varlon='glamt' ; varlat='gphit' ; fill='tmask' ;;
  esac

  # Apply the input mask
  cdo selvar,${var} ${restart_in}.nc  ${var}_${restart_in}_withoutmask.nc 
  applymask maskin_lev0.nc $fill ${var}_${restart_in}_withoutmask.nc $var ${var}_${restart_in}.nc

  # Horizontal extrapolation and fillup the empty seas with a climatology
  extrap ${var}_${restart_in}.nc ${var} ${meshmaskin} ${varlon} ${varlat} Ptoextrap_lev0.nc Ptofillclim_lev0.nc ${fill} ${var}_${restart_out}_int.nc 2d $cfutools $confout $mon
 
  # Apply the output mask
  applymask mask_lev0.nc $fill ${var}_${restart_out}_int.nc $var ${var}_${restart_out}.nc

  # Pasting the output to ${restart_out}.nc
  gathervar ${restart_out}.nc ${var}_${restart_out}.nc
#  rm -f ${var}_${restart_out}.nc ${var}_${restart_out}_int.nc ${var}_${restart_in}.nc
done

#  rm -f Ptoextrap_lev0.nc Ptofillclim_lev0.nc mask2din.nc mask_lev0.nc tmpmask.nc maskin_lev0.nc
if [[ -e Ptoextrap.nc ]] ; then rm -f Ptoextrap.nc ; fi
