#!/bin/bash
#
# extracts additional timeseries for volcanoe analysis from raw data.
# ralf.hand@giub.unibe.ch, 08.11.2021

set -ex

echo "running on $(hostname), PID: $$"

module load cdo/1.9.10

export cdo=cdo
export tmpdir_base="/scratch3/ralf/spielwiese"
export datadir=/mnt/climstor/ERC_PALAEO
export datadir=/mnt/climstor/ERC_PALAEO_tmp
export outdir=/mnt/climstor/ERC_PALAEO

setlist="HIPPO_set_1850_1 HIPPO_set_1850_2 HIPPO_set_1850_3 HIPPO_set_1850_4 HIPPO_set_1420_1 HIPPO_set_1420_2"
setlist="HIPPO_set_1780_1 HIPPO_set_1780_2"
setlist="HIPPO_set_1780_1"
volc_yearlist="1815 1835"

yearlist=$(for year in ${volc_yearlist}; do seq ${year} $(( ${year} + 3 )); done)
yearlist_comsep=$(echo ${yearlist} | tr " " ",")

olddir=$(pwd)

for set in ${setlist}; do

   export set

   cd ${datadir}/${set}

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

   function extract_volc {

      run=${1}
      year=${2}

      $cdo after ${datadir}/${set}/${run}/rawdata/${run}_${year}??.01_echam tmp.${run}.${year}.nc << __EOF__ 
         &select
         code = 131, 132, 156, 239 
         level = -1
         interval = 0 
         type = 70
         format = 4
         mean = 0
         /
      
__EOF__

   $cdo -O -r -f nc -t echam6 \
      chname,var239,pott \
      -setattribute,var239@units=K,var239@long_name="potential temperature" \
      -setcodetab,echam6 \
      tmp.${run}.${year}.nc ${outdir}/${run}/means/${run}_${year}_6h.volc.nc &&
  rm tmp.${run}.${year}.nc

   }

   export -f extract_volc

   # merge

   for year in ${yearlist}; do

      export year

      eval ls -d ${datadir}/${set}/HIPPO_r???i????p?f???? | awk -F / '{print $NF}' | xargs -n1 -P10 -I% bash -c "extract_volc % ${year}"

      echo "year ${year} finished"

   done # year in yearlist

   cd ${olddir}
   rm -rf ${tmp}
 
done # set in setlist

exit 0
