#!/bin/bash
#
# computes annual and seasonal means for the ModE-Sim ensemble
# 
# ralf.hand@giub.unibe.ch 2020-03-25, adapted to ModE-Sim, 2023-04-04

set -ex 


exp=ModE-RA
dir=/tank/exports/ERC_PALAEO/${exp}/outdata


setlist="lowres_20mem_Set_1420-3_1850-1"
varlist="temp2 totprec slp geopoth_50000"
tslist="mam jja son djf year"

oldpwd=$(pwd)

for set in ${setlist}; do
   for var in ${varlist}; do

      set +e; memberlist=$(ls -d ${dir}/${set}/abs/m[0-9][0-9][0-9] 2>/dev/null | sed -e "s&.*/&&"); set -e
      # memberlist=m001

      for member in ${memberlist}; do

         fyear=1420
         lyear=2009

         mondir=${dir}/${set}/abs/${member}/by_var/mon
         if [ ! -d ${mondir} ]; then exit 1 ; fi

         for ts in ${tslist}; do

            tsdir=${dir}/${set}/abs/${member}/by_var/${ts}

            if [ ! -d ${tsdir} ]; then mkdir -p ${tsdir} ; fi

            case ${ts} in
               mam|jja|son) 
                  cdo seasmean -selseas,${ts} ${mondir}/${exp}_${member}_${var}_abs_${fyear}-${lyear}_mon.nc ${tsdir}/${exp}_${member}_${var}_abs_${fyear}-${lyear}_${ts}.nc
                  ;;
               djf)
                  cdo seasmean -selseas,${ts} -seldate,${fyear}-03-01,${lyear}-11-30 ${mondir}/${exp}_${member}_${var}_abs_${fyear}-${lyear}_mon.nc ${tsdir}/${exp}_${member}_${var}_abs_${fyear}-${lyear}_${ts}.nc
                  ;; 
               year)
                  cdo yearmean ${mondir}/${exp}_${member}_${var}_abs_${fyear}-${lyear}_mon.nc ${tsdir}/${exp}_${member}_${var}_abs_${fyear}-${lyear}_${ts}.nc
                  ;;
            esac

         done # ts
 
      done # member
 
      cd ${oldpwd}
   done # var
done # set

exit 0
