#!/bin/bash

set -ex

export cdo=/usr/bin/cdo
workdir="/scratch3/jfranke/ModE-Sim/blocks"
basedir="/mnt/climstor/ERC_PALAEO/ModE-Sim/outdata"

setlist="set_1850-1 set_1850-2 set_1420-1 set_1420-2 set_1420-3"

#olddir=$(pwd)
counter=1
for set in ${setlist}; do

   cd ${basedir}/${set}/abs

#   for exp in $(ls -d HIPPO_r0*i*p*f*); do
   for exp in $(ls -d m*); do # exp = member
     if [[ "$counter" -gt 58 ]]; then # to restart processing with 5th member of first set
      export exp
      if [ ! -d ${workdir}/${set}_${exp} ] ; then mkdir ${workdir}/${set}_${exp} ; fi
      cd ${workdir}/${set}_${exp}
#      tmp=$(mktemp -d ${tmpdir_base}/tmp.create_timeseries.XXX)
#      cd ${tmp}
      cdo -a copy ${basedir}/${set}/abs/${exp}/by_var/6h/ModE-Sim_${set}_${exp}_geopoth_50000_abs_????-????_6h.nc z500.nc
      pids=()
#      infile=${basedir}/${set}/abs/${exp}/timeseries/6h/${exp}_geopoth500_6h.nc
      #infile=${basedir}/${set}/abs/${exp}/by_var/6h/ModE-Sim_${set}_${epx}_geopoth_50000_abs_????-????_6h.nc
      infile=z500.nc
      f90_tm2d=~/blocks/TM2D/tm2d
      invar=geopoth
      pers=20
      ovlp=0.7

      ${f90_tm2d} --infile=${infile} --invar=${invar} --outfile=ModE-Sim_${set}_${exp}_blocks.nc --mode=TM2D --persistence=${pers} --overlap=${ovlp}

#      mv blocks.nc ${basedir}/${exp}/timeseries/6h/${exp}_tm2d_blocks_6h.nc
#      mv blockstat.txt ${basedir}/${exp}/timeseries/6h/${exp}_tm2d_blockstat.txt
#      mv blockstat_all.txt ${basedir}/${exp}/timeseries/6h/${exp}_tm2d_blockstat_all.txt
#      mv blocktracks.txt ${basedir}/${exp}/timeseries/6h/${exp}_tm2d_blocktracks.txt
#      mv blocktracks_all.txt ${basedir}/${exp}/timeseries/6h/${exp}_tm2d_blocktracks_all.txt

      rm z500.nc

#      xargs -n1 -P165 -I% bash -c 'year=$(${cdo} showyear % | sed -e "s/ //g") && ${cdo} -f nc -t echam -selvar,${varname} % ${tmp}/${exp}.${var}.${year}.nc ; pids+=($!)'

      for pid in "${pids[@]}"; do  
         wait "$pid"  # quit if any of the subprocesses failed
      done
    fi
    counter=$((counter+1))
#      cd ${olddir} 

   done # exp

done # set in setlist

exit 0
