#/bin/bash
#
# computes the enstemble statistics for the by_var files
# 
# Ralf Hand, 27.07.2023

set -ex

exp=ModE-RA

setlist="lowres_20mem_Set_1420-3_1850-1 hires_5mem"
varlist="temp2 totprec slp geopoth_50000 geopoth_20000"
levellist="toasurf"
statlist="ensmean ensstd ensmin ensmax"

tslist="mon year mam jja son djf"

base_dir=/tank/exports/ERC_PALAEO

for ts in ${tslist}; do
   for var in ${varlist}; do
      for level in ${levellist}; do
   
         case ${level} in
            toasurf) varname=${var} ;;
            *)       varname=${var}_${level} ;;
         esac
   
         for set in ${setlist}; do
   
            outdir=/${base_dir}/${exp}/outdata/${set}/abs/ensstat/by_var/${ts}
            if [ ! -d ${outdir} ] ; then mkdir -p ${outdir}; fi
   
            fyear=1421
            lyear=2008
 
            infiles=$(ls ${base_dir}/${exp}/outdata/${set}/abs/m???/by_var/${ts}/${exp}_${set}_m???_${varname}_abs_${fyear}-${lyear}_${ts}.nc )
            
            for stat in ${statlist}; do
   
               case ${stat} in
                  ensmean|ensstd|ensmin|ensmax) enscmd=${stat} ;;
                  enspctl125) enscmd="enspctl,12.5" ;;
                  enspctl875) enscmd="enspctl,87.5" ;;
               esac # stat
   
               outfile=${outdir}/ModE-RA_${set}_${stat}_${varname}_abs_${fyear}-${lyear}_${ts}.nc
   
               cdo --no_history -setreftime,1400-01-01,00:00:00 -${enscmd} ${infiles} ${outfile}
   
               case ${stat} in
                  ensmean) member_cmd="ensemble mean of set $(echo ${set} | sed -e "s/_/ /g")" ;;
                  ensstd) member_cmd="ensemble standard deviation of set $(echo ${set} | sed -e "s/_/ /g")" ;;
                  ensmin) member_cmd="ensemble minimum of set $(echo ${set} | sed -e "s/_/ /g")" ;;
                  ensmax) member_cmd="ensemble maximum of set $(echo ${set} | sed -e "s/_/ /g")" ;;
                  enspctl125)  member_cmd="12.5th ensemble percentile of set $(echo ${set} | sed -e "s/_/ /g")" ;;
                  enspctl875)  member_cmd="87.5th ensemble percentile of set $(echo ${set} | sed -e "s/_/ /g")" ;;
               esac # member
   
               ncatted -h \
                  -a set,global,m,c,"${set}" \
                  -a member,global,m,c,"${member_cmd}" \
                  -a creation_date,global,m,c,"$(date +"%Y-%m-%d %H:%M:%S %Z")" \
                 ${outfile}
   
            done # stat         
         done # set
      done # level
   done # var
done # ts

exit 0
