#/bin/bash
#
# computes indices based on pooled ensemble statistics.
# ralf.hand@giub.unibe.ch, 02.07.2020

set -ex
shopt -s extglob


tmp=$(mktemp -d /scratch3/ralf/spielwiese/tmp.ensstat.XXX)
cd ${tmp}

expdir=/mnt/climstor/ERC_PALAEO

fyear=1451
lyear=1781

width=3

varlist="slp"

set=HIPPO_set_1420_1

for year in $(seq $(( ${fyear} + ${width} ))  $(( ${lyear} - ${width} )) ) ; do

   for run in $(ls -d ${expdir}/${set}/HIPPO_r???i????p*f* | xargs -n 1 basename ); do

      if [ ! -d ${expdir}/${set}/pooled_indices ]; then mkdir ${expdir}/${set}/pooled_indices; fi

      for var in ${varlist}; do
         for year2 in $(seq $(( ${year} - ${width})) $(( ${year} + ${width}))); do

            if [ ! -e tmp.${run}.${year2}.${var}.nc -a -e ${expdir}/${run}/means/${run}_${year2}_mon.toasurf.nc ]; then 
               cdo selvar,${var} ${expdir}/${run}/means/${run}_${year2}_mon.toasurf.nc tmp.${run}.${year2}.${var}.nc
            elif [ ! -e ${expdir}/${run}/means/${run}_${year2}_mon.toasurf.nc ]; then
               echo "!!! WARNING: ${expdir}/${run}/means/${run}_${year2}_mon.toasurf.nc does not exist. Skip" 
            fi 

         done # year2
      done # var

      if [ $(eval ls tmp.${run}.{$(( ${year} - ${width} ))..$(( ${year} + ${width} ))}.${var}.nc 2>/dev/null | wc -w) -gt 1 ]; then
            eval cdo mergetime $(eval ls tmp.${run}.{$(( ${year} - ${width} ))..$(( ${year} + ${width} ))}.${var}.nc 2>/dev/null | tr "\n" ' ') tmp.${run}.chunk.${year}.${var}.nc
      else
         pwd # exit 98
      fi

   done # run

   pwd

   eval ls tmp.HIPPO_r???i????p*f+([0-9]).{$(( ${year} - ${width} ))..$(( ${year} + ${width} ))}.${var}.nc

   nfiles=$(eval ls tmp.HIPPO_r???i????p*f+([0-9]).{$(( ${year} - ${width} ))..$(( ${year} + ${width} ))}.${var}.nc 2>/dev/null  | wc -w)
   echo ${nfiles}

   if [ ${nfiles} -gt 45 ]; then
      concatenate_runs.bash  tmp.*.chunk.${year}.${var}.nc tmp.chunk.${year}.${var}.nc
      compute_NAO.bash tmp.chunk.${year}.slp.nc
      cdo setyear,${year} tmp.chunk.${year}.slp_NAO_timeseries.nc ${expdir}/${set}/pooled_indices/${set}_$(( ${year} - ${width} ))-$(( ${year} + ${width} ))_width_${width}_NAO_timeseries.nc
      cdo setyear,${year} tmp.chunk.${year}.slp_NAO_pattern.nc ${expdir}/${set}/pooled_indices/${set}_$(( ${year} - ${width} ))-$(( ${year} + ${width} ))_width_${width}_NAO_pattern.nc
   fi

done # year

pwd

exit 0
