#!/bin/bash

set -ex

export cdo=/usr/bin/cdo
tmpdir_base="/scratch3/ralf/spielwiese"
basedir=/mnt/climstor/ERC_PALAEO

setlist="HIPPO_set_1850_2 HIPPO_set_1850_3 HIPPO_set_1850_4 HIPPO_set_1420_1 HIPPO_set_1420_2"
setlist="HIPPO_set_1780_2"

olddir=$(pwd)

for set in ${setlist}; do

   cd ${set}

   for exp in $(ls -d HIPPO_r0*i*p*f*); do
#   for exp in $(ls -d HIPPO_r0{28..40}i1420p1f13??); do

      export exp
      tmp=$(mktemp -d ${tmpdir_base}/tmp.create_timeseries.XXX)
      cd ${tmp}

      pids=()

      infile=${basedir}/${exp}/timeseries/6h/${exp}_geopoth500_6h.nc
      f90_tm2d=tm2d
      invar=geopoth
      pers=20
      ovlp=0.7

      ${f90_tm2d} --infile=${infile} --invar=${invar} --outfile=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

#      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
 
      cd ${olddir} 

   done # exp

done # set in setlist

exit 0
