#!/bin/bash

set -evx 
# 
# This script extrapolates horizontally, interpolates horizontally and interpolates vertically 
# the scalar fields 
#
# History : Eleftheria Exarchou  - Initial version           June 2015 
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#                                Arguments
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# The masks of the input file, which here is in ORAP5 ORCA05L75 
# and the output file, which is the ORCA01L46
maskin='mesh_mask_nemo.Ec3.0_O25L75.nc' 
maskout='mesh_mask_nemo.Ec3.0_O1L46.nc'

dirhigh=/esnas/releases/ic/ocean/ORCA025L75/ORAP5/
dirlow=/esnas/releases/ic/ocean/ORCA1L46/ORAP5/
curdir=`pwd`


listdates=( '0430' '1031'  )

for year in {1993..2013} ; do 
	echo $year 

for date in ${listdates[@]} ; do
file_final=ORAP5_fc0_${year}${date}_restart 

        # check if interpolated file exists already in esnas
	if [ ! -e  /esnas/releases/ic/ocean/ORCA1L46/ORAP5/${file_final}.nc.gz ] ; then   
	# check if the HR file exists 
	if  [  -e ${dirhigh}/ORAP5_fc0_${year}${date}_restart.nc.gz ] ; then  
        # check if file is locally here already (or: use gunzip -f to force overwrite, but this is slower )
	if [ ! -e  ${curdir}/ORAP5_fc0_${year}${date}_restart.nc ] ; then   
	gunzip -c  ${dirhigh}/ORAP5_fc0_${year}${date}_restart.nc.gz   > ${curdir}/ORAP5_fc0_${year}${date}_restart.nc
        fi 
	# Input/output restart file names 
	restart_in=ORAP5_fc0_${year}${date}_restart  
	restart_out=ORAP5_fc0_${year}${date}_restart_int



   listvars3d=( 'en' 'avt' 'avm' 'avmu' 'avmv' 'dissl' 'un' 'vn' 'tn' 'sn' 'rotn' 'hdivn' 'rhop' 'ub' 'vb' 'tb' 'sb' 'rotb' 'hdivb' 'ssu_m' 'ssv_m' 'sst_m' 'sss_m' 'ssh_m' 'rnf_b' 'rnf_hc_b' 'rnf_sc_b' 'utau_b' 'vtau_b' 'qns_b' 'emp_b' 'emps_b' 'sshn sshb' 'gcx' 'gcxb' )
   varscopy='nn_fsbc,rdt,rdttra1,kt,ndastp,adatrj,slim'


# Create the initial restart file with the basic set of 0 dimensional variables 
if [[ ! -e ${restart_out}.nc ]] ; then
ncks -O -v $varscopy ${restart_in}.nc ${restart_out}.nc
ncks -A -v nav_lon,nav_lat,nav_lev    $maskout ${restart_out}.nc
fi 

# Specify the masks etc that correspond to each variable
for var in ${listvars3d[@]} ; do
  case $var in
   'avmu'|'un'|'ub') mask='umask' ; interp3d='0'  ;;
   'ssu_m'|'utau_b') mask='umask' ; interp3d='1'  ;;
   'avmv'|'vn'|'vb') mask='vmask' ; interp3d='0'  ;;
   'ssv_m'|'vtau_b') mask='vmask' ; interp3d='1'  ;;
   'rotb'|'rotn')    mask='fmask' ; interp3d='0'  ;;
   'avt'|'avm'|'en'|'dissl'|'hdivb'|'hdivn'|'rhop'|'sn'|'tn'|'sb'|'tb') mask='tmask' ; interp3d=0  ;;
   'qns_b'|'emp_b'|'emps_b'|'sst_m'|'sss_m'|'ssh_m'|'rnf_b'|'rnf_hc_b'|'rnf_sc_b') mask='tmask' ; interp3d=1  ;;
   'gcx'|'gcxb'|'sshb'|'sshn')  mask='tmask' ;  interp3d=1  ;;
  esac


# Check if interpolation for this particular variable is already done 
if [ ! -e ${var}_ORCA025-ORCA1_restart_${year}${date}_miss.nc ] ;  then 

file_in=${var}_in.nc 
ncks -O  -v ${var},nav_lon,nav_lat,nav_lev,time_counter ${restart_in}.nc $file_in
ncrename -d t,time  $file_in

cat <<EOF > namelist_$var 

!! ------------------- 
!! Namelist for SOSIE 
!! ------------------- 
!! 
!! 
!! *********************** 
!! Input characteristics : 
!! *********************** 
!! 
!! ivect : vector correction control on treated field [integer] 
!!         ivect = 0 : input field is not a component of a vector 
!!         or the target grid is regular (lregout = T) 
!!         * if non-regular distorted target grids (like ORCAX): 
!!         ivect = 1 : input field is a zonal (X) component of a vector 
!!         ivect = 2 : input field is a meridional (Y) component of a vector 
!! 
!! lregin : is the source grid regular? [logical] 
!!          (ie : are input longitude and latitude 1D?) 
!! 
!! cf_in   : file containing the input field to be interpolated [char]
!! cv_in   : name of treated variable (in input field file) [char]
!!
!! cv_t_in : name of time record variable in the input file [char]
!!           or 'missing_rec' if no time record is present in the input file
!!
!! jt1     : first time record to be interpolated
!! jt2     : last  time record to be interpolated
!!           => set jt1 and jt2 to 0 if you want to skip this option 
!!              and interpolate the nt time steps of the current field
!! 
!! jplev : level to treat if your file is 3D (spatial), has no influence if 
!!         your file is 2D !
!!         jplev > 0 = level to treat (ex : jplev = 1 will interpolate only 
!!                     surface field corresponding to the 1st level )
!!       ------------------------------------------------------------------
!!       | jplev = 0 : perform 3D interpolation (if input file is 3D) !!! |
!!       ------------------------------------------------------------------
!!
!! cf_x_in   : file containing the input grid (usually = cf_in) [char] 
!! cv_lon_in : name of longitude in the input grid file [char] 
!! cv_lat_in : name of latitude in the input grid file [char] 
!! 
!! cf_lsm_in : file containing the input land-sea mask [char]
!!             or specify 'missing_value' if a 'missing_value' netcdf
!!             attribute defines the mask on the input data field
!!             (not needed if "ldrown = .FALSE." --> '')

!! cv_lsm_in : name of land-sea mask variable [char]
!!             (not needed if "ldrown = .FALSE." 
!!              or if cf_lsm_in = 'missing_value'--> '')
!!             by default ocean is flagged with value 1
!!             and continents are flagged with value 0
!!
!! ldrown : whether we call DROWN land filling procedure [logical] 
!!
!! ewper : east-west periodicity on the input file/grid [integer] 
!!         = -1 --> no periodicity 
!!         >= 0 --> periodicity with overlap of ewper points 
!! 
!! vmax : upper bound not to exceed for treated variable [real] 
!! vmin : lower bound not to exceed for treated variable [real] 
!!-------------------------------------------------------------------------- 
!! 
&ninput
ivect     = 0
lregin    = F  ! F becuase the input grid is not regular 
cf_in     = '$file_in'
cv_in     = '${var}'
cv_t_in   = 'time_counter' 
jt1       = 0   ! sdfgdfhgdfgh
jt2       = 0
jplev     = $interp3d  ! use 0 for 3D interpolation 
cf_x_in   = '$file_in' 
cv_lon_in = 'nav_lon'
cv_lat_in = 'nav_lat'
cf_lsm_in = '$maskin'
cv_lsm_in = '$mask'
ldrown    = T
ewper     = 0
vmax      =  1.E10
vmin      = -1.E10
/
!!
!!
!!
!!
!! ***********************************
!!  IF 3D INTERPOLATION ( jplev = 0 )
!! ***********************************
!!
!! Only mind if you do want to perform a 3D (spatial) interpolation
!! 
!! Mind only if you do want to perform a 3D interpolation !
!! First, make sure that jplev is set to 0 !
!!
!! cf_z_in  : file containing the input depth vector (associates a depth to a 
!!            given level). In most cases should be the same file than cf_x_in.
!! cv_z_in  : name of the variable for the input depth vector
!!
!! cf_z_out : file containing the output depth vector (associates a depth to a 
!!            given level). In most cases should be the same file than cf_x_in.
!! cv_z_out : name of the variable for the output depth vector in file 'cf_z_out'
!! cv_z_out_name: name you wish to give to depth variable in file to be created...
!!
!!
&n3d
cf_z_in  = '$file_in'
cv_z_in  = 'nav_lev'
cf_z_out = '$maskout'
cv_z_out = 'nav_lev'
cv_z_out_name = 'lev'
/
!! 
!!
!!
!!
!!
!! ***************************** 
!! Output Grid characteristics : 
!! ***************************** 
!! 
!! lregout : is the target grid regular ? [logical] 
!!           (ie : are output longitude and latitude 1D?) 
!!
!! cf_x_out   : file containing the target grid [char] 
!! cv_lon_out : name of longitude variable [char] 
!! cv_lat_out : name of latitude variable [char] 
!!
!! TRICK:  for interpolating onto a global regular spherical grid
!! ------  with a resolution of dx deg. of longitude and dy deg. of latitude
!!         * cf_x_out   = 'spheric' ! tells SOSIE to build a spherical output grid
!!         * cv_lon_out = '1.0'  ! your dx, here 1.0 deg. 
!!         * cv_lat_out = '1.0'  ! your dy, here 1.0 deg.
!!
!!
!! cf_lsm_out : file containing output land-sea mask [char] 
!!              MUST BE 3D for 3D interpolation!
!!              or specify 'missing_value' if a 'missing_value' netcdf
!!              attribute defines the mask on a field 'X' in file 'cf_x_out'
!!              (not needed if "lmout = .FALSE." --> '') 
!!
!! cv_lsm_out : name of land-sea mask variable in 'cf_lsm_out'     [char]
!!              or name of field 'X' in 'cf_x_out' if you specified 
!!              cf_lsm_out = 'missing_value'
!!              (not needed if "lmout = .FALSE." --> '') 
!!
!! lmout : whether to mask the interpolated field on the output file [logical] 
!!
!! rmaskvalue : missing value given to output field (for continents) [logical] 
!!
!! lct   : whether to control or not time variable [logical] 
!!         TRUE -> specify time array with starting time 't0' and step 't_stp' 
!!         FALSE -> same time array as in input file is used 
!! t0    : time to start (if lct is set to .TRUE.) [real] 
!! t_stp : time step (if lct is set to .TRUE.) [real] 
!!
!!
&noutput
lregout    = F   ! the output grid is not regular
cf_x_out   = '$maskout'
cv_lon_out = 'nav_lon'
cv_lat_out = 'nav_lat'
cf_lsm_out = '$maskout'
cv_lsm_out = '$mask'
lmout      = T
rmaskvalue = 1.e+20 ! -9999.
lct        = F
t0         = 0.
t_stp      = 0.25
/
!! 
!! 
!! 
!! 
!! ******************************* 
!! Netcdf output characteristics : 
!! ******************************* 
!! 
!! This mostly deals with how the output file to be created is going to look like!
!!
!! cmethod  : the 2D interpolation method to be used
!!            use 'akima' if your input domain is regular (non-distorted grid)
!!            use 'bilin' otherwise, which is bilinear 2D interpolation
!!
!! *** Into the netcdf file to be created : *** 
!! cv_l_out : name for longitude on the output file [char] 
!! cv_p_out : name for latitude on the output file [char] 
!! cv_t_out : name for time on the output file [char] 
!! cv_out   : name for treated variable on the output file [char] 
!! cu_out   : treated variable units [char] 
!! cu_t     : time unit [char]
!! cln_out  : treated variable long name [char] 
!! cd_out   : directory to create output file to [char]
!! 
!! *** Name of the output file : *** 
!! csource  : short string to describe origin of the file [char] 
!! ctarget  : short string to describe the target grid [char] 
!! cextra   : short extra indication about the file [char] 
!! 
&nnetcdf
cmethod  = 'bilin'
cv_l_out = 'x'  ! 'var_lon'
cv_p_out = 'y'  ! 'var_lat'
cv_t_out = 'time_counter'
cv_out   = '${var}'
cu_out   = ' '
cu_t     = 'unknown'
cln_out  = ' '
cd_out   = '.'
csource  = 'ORCA025'
ctarget  = 'ORCA1'
cextra   = 'restart_${year}${date}'
/ 
!!


EOF

./sosie.x  -f namelist_$var 


cdo setmisstoc,0  ${var}_ORCA025-ORCA1_restart_${year}${date}.nc  ${var}_ORCA025-ORCA1_restart_${year}${date}_miss.nc

ncks -A ${var}_ORCA025-ORCA1_restart_${year}${date}_miss.nc  ${restart_out}.nc 

rm -rf  ${var}_ORCA025-ORCA1_restart_${year}${date}_*.nc   
fi
done 


# Some variables have negative values in some points, 
# whereas they should be always positive. We fix it by
# making these values equal to 0. These vars are 
# avt,avm,avmu,avmv,dissl 

file1=ORAP5_fc0_${year}${date}_restart_int.nc   
file2=ORAP5_fc0_${year}${date}_restart_int_needtofix.nc                              
file3=ORAP5_fc0_${year}${date}_restart_int_fixed.nc                   
file4=ORAP5_fc0_${year}${date}_restart_int_valuesfixed.nc    
file5=ORAP5_fc0_${year}${date}_restart_int_valuesfixed_percision.nc    

cdo selvar,avt,avm,avmu,avmv,dissl  $file1  $file2
cdo setrtoc,-1000000000,0,0         $file2  $file3

cdo replace  $file1     $file3  $file4
cdo  -b 64 copy         $file4  $file5 

gzip -c  $file5  >  /esnas/releases/ic/ocean/ORCA1L46/ORAP5/${file_final}.nc.gz 
rm  -rf  ${curdir}/ORAP5_fc0_${year}${date}_restart.nc

fi 
fi 
done 
done 


