#!/bin/bash
#
# adapts variable and meta data information to the ModE standard 
#
# ralf.hand@giub.unibe.ch, 01.11.2023

# set -ex

tslist="mon son mam djf jja year"
varlist="temp2 totprec slp geopoth_20000 geopoth_50000"
setlist="hires_5mem lowres_20mem_Set_1420-3_1850-1"

tslist="mon"
varlist="geopoth_20000 geopoth_30000 omega_50000 u10 u_50000 u_85000 v10 v_50000 v_85000"
setlist="hires_5mem lowres_20mem_Set_1420-3_1850-1"

outputtype="abs"

fyear=1421
lyear=2008

dir_base=/tank/exports/ERC_PALAEO/ModE-RA/outdata
outdir_base=/tank/exports/ERC_PALAEO/ModE-RA/outdata

# col_final_lyear=$(head -1 ${overviewfile} | awk -F ";" -v b="final_lyear" '{for (i=1;i<=NF;i++) { if ($i == b) { print i } }}')

for set in ${setlist}; do

   set +e; export memberlist=$(ls -d ${dir_base}/${set}/${outputtype}/m[0-9][0-9][0-9] 2>/dev/null | sed -e "s&.*/&&"); set -e

   for member in ${memberlist} ensmean ensstd ensmin ensmax; do

      case ${member} in
         m[01]??) 
               member_dirname=${member}
               ;;

         ensmean|ensstd|ensmin|ensmax|enspctl125|enspctl875) 
               member_dirname=ensstat 
               ;;

       esac # member

       for ts in ${tslist}; do
   
          for var in ${varlist}; do
   
             indir=${dir_base}/${set}/${outputtype}/${member_dirname}/by_var/${ts}
             outdir=${outdir_base}/${set}/${outputtype}/${member_dirname}/by_var/${ts}

             infile=${indir}/ModE-RA_${set}_${member}_${var}_${outputtype}_${fyear}-${lyear}_${ts}.nc
             outfile=${outdir}/ModE-RA_${set}_${member}_${var}_${outputtype}_${fyear}-${lyear}_${ts}.nc

             if [ ! -e ${outdir} ]; then mkdir -p ${outdir}; fi

             orig_varname=$(cdo -s showvar ${infile} | sed -e "s/ //g")

             case ${var} in

                # surface/2D variables

                temp2)
                       var_new=${var}
                       long_name='2m air temperature'
                       standard_name="air_temperature"
                       ;;
          
                slp)   
                       var_new=${var}
                       long_name='mean sea level pressure'
                       standard_name="air_pressure_at_mean_sea_level"
                       ;;
          
                totprec)
                       var_new=${var}
                       long_name='total precipitation'
                       standard_name="precipitation_flux"
                       ;;

                 u10)  
                       var_new=${var}
                       long_name='10m u-velocity'
                       standard_name='eastward_wind'
                       ;;

                 v10)
                       var_new=${var}
                       long_name='10m v-velocity'
                       standard_name='northward_wind'
                       ;;

                 # 3D variable
    
    	           geopoth_*)
                       var_new=$(echo ${var} | awk -F '_' '{print $1}')
                       lev=$(echo "$(echo ${var} | awk -F '_' '{print $2}') / 100" | bc)
                       long_name="${lev} hPa geopotential height"
                       standard_name="geopotential_height"
                       ;;
          
                  u_*)
                       var_new=$(echo ${var} | awk -F '_' '{print $1}')
                       lev=$(echo "$(echo ${var} | awk -F '_' '{print $2}') / 100" | bc)
                       long_name="${lev} hPa u-wind"
                       standard_name="eastward_wind"
                       ;;
    
                  v_*)
                       var_new=$(echo ${var} | awk -F '_' '{print $1}')
                       lev=$(echo "$(echo ${var} | awk -F '_' '{print $2}') / 100" | bc)
                       long_name="${lev} hPa v-wind"
                       standard_name="northward_wind"
                       ;;
    
                  omega_*)
                       var_new=$(echo ${var} | awk -F '_' '{print $1}')
                       lev=$(echo "$(echo ${var} | awk -F '_' '{print $2}') / 100" | bc)
                       long_name="${lev} hPa vertical velocity"
                       standard_name="lagrangian_tendency_of_air_pressure"
                       ;;
    
             esac   # var

             orig_varname=$(echo ${var} | awk -F '_' '{print $1}')

             case ${member} in
                m0??) member_cmd="${member/m/}" ;;
                ensmean) member_cmd="ensemble mean of set ${set}\"" ;;
                ensstd) member_cmd="ensemble standard deviation of set ${set}" ;;
                ensmin) member_cmd="ensemble minimum of set ${set}" ;;
                ensmax) member_cmd="ensemble maximum of set ${set}" ;;
                enspctl125)  member_cmd="12.5th ensemble percentile of set ${set}" ;;
                enspctl875)  member_cmd="87.5th ensemble percentile of set ${set}" ;;
             esac # member
   
             cdo -O setvar,${var_new} -setreftime,1400-01-01,00:00:00 -settunits,seconds ${infile} tmp.nc       
         
             ncatted -O -h \
              -a long_name,${var_new},m,c,"${long_name}" \
              -a standard_name,${var_new},c,c,"${standard_name}" \
              -a institution,${var_new},d,, \
              -a history,global,d,, \
              -a title,global,c,c,'ModE-RA - A 600-year long global monthly paleo-reanalysis of the Modern Era' \
              -a creator,global,c,c,'The PALAEO-RA project group' \
              -a institution,global,m,c,Oeschger\ Centre\ for\ Climate\ Change\ Research \
              -a contact,global,c,c,'Joerg Franke (https://orcid.org/0000-0001-7897-4225)' \
              -a experiment,global,c,c,"ModE-RA" \
              -a set,global,c,c,"${set}" \
              -a member,global,c,c,"${member_cmd}" \
              -a creation_date,global,c,c,"$(date +"%Y-%m-%d %H:%M:%S %Z")" \
              tmp.nc ${outfile}

              rm tmp.nc

         done # var

      done # ts

   done # member

done # set

exit 0
