#!/usr/bin/bash

BASE_PATH="/home/study/S24_Kangur"
TEMP_DIR="${BASE_PATH}/Temp"
RESULT_DIR="${BASE_PATH}/Results"
DATA_DIR="/mnt/hpc/public/mko/CMEMS/BS_ice_conc"

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

mkdir -p "$TEMP_DIR"
mkdir -p "$RESULT_DIR"

for year in {2002..2012}; do
  echo "Processing year: $year"
  for month in {01..12}; do
    cdo $cdo_options mergetime ${DATA_DIR}/BS_SAT_SST.day.${year}${month}*.nc \
       ${TEMP_DIR}/temporary.${year}${month}.nc
    cdo $cdo_options selvar,sea_ice_fraction \
       -sellonlatbox,21,30,57,61 \
       ${TEMP_DIR}/temporary.${year}${month}.nc \
       ${TEMP_DIR}/ice_data.${year}${month}.nc
    rm -f ${TEMP_DIR}/temporary.${year}${month}.nc
  done
  cdo $cdo_options mergetime ${TEMP_DIR}/ice_data.${year}*.nc \
     ${RESULT_DIR}/yearly_ice_data.${year}.nc
done

cdo $cdo_options mergetime ${RESULT_DIR}/yearly_ice_data.*.nc \
   ${RESULT_DIR}/combined_ice_data.nc
cdo $cdo_options yearsum -gtc,0 \
   ${RESULT_DIR}/combined_ice_data.nc \
   ${RESULT_DIR}/annual_ice_days.nc
cdo $cdo_options timavg \
   ${RESULT_DIR}/annual_ice_days.nc \
   ${RESULT_DIR}/average_ice_days.nc
   
cdo $cdo_options sellonlatbox,23.3,30,59,61 \
   ${RESULT_DIR}/combined_ice_data.nc \
   ${TEMP_DIR}/ice_GOF.nc
cdo $cdo_options -gtc,0 \
   ${TEMP_DIR}/ice_GOF.nc \
   ${TEMP_DIR}/presence_GOF.nc
cdo $cdo_options fldsum \
   ${TEMP_DIR}/presence_GOF.nc \
   ${TEMP_DIR}/total_GOF.nc
cdo $cdo_options ydaymean \
   ${TEMP_DIR}/total_GOF.nc \
   ${RESULT_DIR}/mean_GOF.nc
cdo $cdo_options ydaystd \
   ${TEMP_DIR}/total_GOF.nc \
   ${RESULT_DIR}/std_GOF.nc

cdo $cdo_options sellonlatbox,22,25,56.5,58.5 \
   ${RESULT_DIR}/combined_ice_data.nc \
   ${TEMP_DIR}/ice_GOR.nc
cdo $cdo_options -gtc,0 \
   ${TEMP_DIR}/ice_GOR.nc \
   ${TEMP_DIR}/presence_GOR.nc
cdo $cdo_options fldsum \
   ${TEMP_DIR}/presence_GOR.nc \
   ${TEMP_DIR}/total_GOR.nc
cdo $cdo_options ydaymean \
   ${TEMP_DIR}/total_GOR.nc \
   ${RESULT_DIR}/mean_GOR.nc
cdo $cdo_options ydaystd \
   ${TEMP_DIR}/total_GOR.nc \
   ${RESULT_DIR}/std_GOR.nc

echo "Deleting temporary directory..."
rm -rf "$TEMP_DIR"
echo "Script completed successfully."

