#!/bin/bash
 
#SBATCH -n 1
#SBATCH -t 60: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=1958
yearf=2013
fc0=4
fcf=4
config='O1L46'
TMPDIR=/scratch/vguemas/$$

mkdir $TMPDIR
cd $TMPDIR
cp /home/vguemas/CFU_tools_new/prep_restarts/script_interp_vert_ocean_outputs.bash .

for ((fc=${fc0};fc<=${fcf};fc++)) ; do
  for ((year=${year0};year<=${yearf};year++)) ; do
    for ((mon=1;mon<=12;mon++)) ; do
# Fetching the input file
      cp /cfu/releases/nudging/ocean/s4/ORCA1/fc${fc}/s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc.gz .
      gunzip s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc.gz
# Vertical interpolation + horizontal and vertical extrapolation + filling empty seas 
      bash script_interp_vert_ocean_outputs.bash s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc votemper ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc $(printf "%02d" $mon) 
      bash script_interp_vert_ocean_outputs.bash s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc vosaline vosaline.nc $(printf "%02d" $mon)
      ncks -A vosaline.nc ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc; rm -f vosaline.nc
# The output file is masked to be able to check the mask but EC-Earth does not accept masks
      cdo setmisstoc,0 ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc tmp.nc; rm -f ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc; mv tmp.nc ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc 
# Formatting
      ncks -O -v vosaline,votemper ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc
      ncecat -O -h ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc
      ncrename -d record,time ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc
# Storage
      gzip ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc
      mv ${config}_s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc.gz /cfu/releases/nudging/ocean/s4/ORCA1L46/fc${fc}/s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc.gz
      rm -f s4_fc${fc}_${year}$(printf "%02d" $mon)_grid_T.nc.gz
    done
  done
done
rm -f script_interp_vert_ocean_outputs.bash
ls
rm -rf $TMPDIR
