#!/bin/bash
 
#SBATCH -n 1
#SBATCH -t 120:00:00
#SBATCH -J oras4_O1L46
#SBATCH --mail-user <virginie.guemas@ic3.cat>
#SBATCH --mail-type FAIL
#SBATCH -o oras4_O1L46-%j.out
#SBATCH -e oras4_O1L46-%j.err

set -evx

year0=1992
yearf=2009
fc0=1
fcf=4
lstMM=( '1031' '0430' )
config='O1L46'
TMPDIR=/scratch/vguemas/$$

mkdir $TMPDIR
cd $TMPDIR
cp /cfu/pub/scripts/prep_restarts/library/comp_rhop_$config comp_rhop
cp /home/vguemas/CFU_tools_new/prep_restarts/script_interp_vert_ocean_restart.bash .
for ((year=${year0};year<=${yearf};year++)) ; do
 for ((fc=${fc0};fc<=${fcf};fc++)) ; do
  for MM in ${lstMM[@]} ; do
   cp /cfu/releases/ic/ocean/ORCA1/s4/s4_fc${fc}_${year}${MM}_restart.nc.gz .
   gunzip s4_fc${fc}_${year}${MM}_restart.nc.gz
   # Vertical interpolation + horizontal and vertical extrapolation + filling empty seas 
   bash script_interp_vert_ocean_restart.bash  s4_fc${fc}_${year}${MM}_restart s4_fc${fc}_${year}${MM}_restart_O1L46 ${MM:0:2}   
   # rhop needs to be added for EC-Earth3 ; computed from tn and sn
   cat > namelist_rhop <<EOF
&density
  input_file = 's4_fc${fc}_${year}${MM}_restart_O1L46.nc'
  input_Tvar = 'tn'
  input_Svar = 'sn'
  input_Dvar = 'nav_lev'
  outfile    = 'rhop_fc${fc}_${year}${MM}.nc'
/
EOF
   ./comp_rhop
   ncwa -O -a t rhop_fc${fc}_${year}${MM}.nc rhop_fc${fc}_${year}${MM}.nc
   ncks -A rhop_fc${fc}_${year}${MM}.nc s4_fc${fc}_${year}${MM}_restart_O1L46.nc
   # The output restart is masked to be able to check the mask
   # but EC-Earth does not accept masks
   cdo setmisstoc,0 s4_fc${fc}_${year}${MM}_restart_O1L46.nc tmp.nc; rm -f s4_fc${fc}_${year}${MM}_restart_O1L46.nc; mv tmp.nc s4_fc${fc}_${year}${MM}_restart_O1L46.nc 
   # Storage
   gzip s4_fc${fc}_${year}${MM}_restart_O1L46.nc
   mv s4_fc${fc}_${year}${MM}_restart_O1L46.nc.gz /cfu/releases/ic/ocean/ORCA1L46/s4/s4_fc${fc}_${year}${MM}_restart.nc.gz
   rm -f s4_fc${fc}_${year}${MM}_restart.nc namelist_rhop rhop_fc${fc}_${year}${MM}.nc
  done
 done
done
rm -f comp_rhop script_interp_vert_ocean_restart.bash
rm -rf $TMPDIR
