#!/usr/bin/env bash

# Directories
BASEDIR="/home/study/S24_sten"
INTDIR="${BASEDIR}/intermediate"
OUTDIR="${BASEDIR}/output"
INDIR="/mnt/hpc/public/mko/CMEMS/BS_ice_conc"

opt='-L -O -f nc4 -z zip1'

# Yearly loop
for yy in {2000..2015}; do
  for mm in {01..12}; do
    cdo $opt mergetime ${INDIR}/BS_SAT_SST.day.${yy}${mm}*.nc \
       ${INTDIR}/tmp.${yy}${mm}.nc
    cdo $opt selvar,sea_ice_fraction \
       -sellonlatbox,21,30,57,61 \
       ${INTDIR}/tmp.${yy}${mm}.nc \
       ${INTDIR}/ice.${yy}${mm}.nc
    rm -f ${INTDIR}/tmp.${yy}${mm}.nc
  done
  cdo $opt mergetime ${INTDIR}/ice.${yy}*.nc \
     ${OUTDIR}/ice_year.${yy}.nc
done

# Merge all years
cdo $opt mergetime ${OUTDIR}/ice_year.*.nc \
   ${OUTDIR}/merged_ice_all.nc
cdo $opt yearsum -gtc,0 \
   ${OUTDIR}/merged_ice_all.nc \
   ${OUTDIR}/year_ice_days.nc
cdo $opt timavg \
   ${OUTDIR}/year_ice_days.nc \
   ${OUTDIR}/avg_ice_days.nc

# Subregion: Gulf of Riga
cdo $opt sellonlatbox,22,25,56.5,58.5 \
   ${OUTDIR}/merged_ice_all.nc \
   ${INTDIR}/ice_GOR.nc
cdo $opt -gtc,0 \
   ${INTDIR}/ice_GOR.nc \
   ${INTDIR}/above_GOR.nc
cdo $opt fldsum \
   ${INTDIR}/above_GOR.nc \
   ${INTDIR}/sum_GOR.nc
cdo $opt ydaymean \
   ${INTDIR}/sum_GOR.nc \
   ${OUTDIR}/mean_ice_extent_GOR.nc
cdo $opt ydaystd \
   ${INTDIR}/sum_GOR.nc \
   ${OUTDIR}/std_ice_extent_GOR.nc

# Subregion: Gulf of Finland
cdo $opt sellonlatbox,23.3,30,59,61 \
   ${OUTDIR}/merged_ice_all.nc \
   ${INTDIR}/ice_GOF.nc
cdo $opt -gtc,0 \
   ${INTDIR}/ice_GOF.nc \
   ${INTDIR}/above_GOF.nc
cdo $opt fldsum \
   ${INTDIR}/above_GOF.nc \
   ${INTDIR}/sum_GOF.nc
cdo $opt ydaymean \
   ${INTDIR}/sum_GOF.nc \
   ${OUTDIR}/mean_ice_extent_GOF.nc
cdo $opt ydaystd \
   ${INTDIR}/sum_GOF.nc \
   ${OUTDIR}/std_ice_extent_GOF.nc

