#!/bin/bash 
#SBATCH -n 1
#SBATCH -t 10:00:00
#SBATCH -J reg_variable
#SBATCH -o /home/Earth/rcruzgar/Desktop/Experiments/area_data/latest_versions/reg_var_IFS.bash-%j.out
#SBATCH --mem=50000

# This script intents to obtain a weighted average from some spatial variable
# in some specific regions (for the IFS variables -in a regular grid already without having interpolated-)

module load CDO/1.7.2-foss-2015a

exp=i019
mon=Amon # Amon (atmosphere), OImon (ice), Omon (ocean)
mask=/esnas/exp/ecearth/mask.regions.ifs_320x160.nc
for var in  hfts ; do  # hfts rst rss tas clt fal psl 
  for reg in CanArch Barents_Sea TotalArc; do #$( cdo showvar $mask ) #LAT80N Beaufort_Sea
    dir=/esnas/exp/ecearth/$exp/monthly_mean/${var}_f6h
    outdir=/esnas/exp/ecearth/$exp/monthly_mean/${var}${reg}_f6h
    mkdir -p $outdir
    if [[ $reg != "lat" ]] && [[ $reg != "lon" ]]; then
      for sd in $( ls /esnas/exp/ecearth/$exp/monthly_mean/${var}_f6h/* | cut -f7 -d"_" | sort -u ); do
        for mb in $( ls /esnas/exp/ecearth/$exp/monthly_mean/${var}_f6h/*${sd}* | cut -f8 -d"_" | sort -u ); do
          for leadtime in $( ls /esnas/exp/ecearth/$exp/monthly_mean/${var}_f6h/*${sd}* | cut -f9 -d"_" | sort -u ); do
 	    file=${var}_${mon}_EC-EARTH_${exp}_${sd}_${mb}_${leadtime} # Amon (atmosphere), OImon (ice), Omon (ocean)
            outfile=${var}${reg}_${mon}_EC-EARTH_${exp}_${sd}_${mb}_${leadtime} 
	    tmpfile=${var}${reg}_${mon}_EC-EARTH_${exp}_${sd}_${mb}_${leadtime}_tmp
	    cdo ifthen -selvar,$reg $mask ${dir}/$file ${outdir}/$outfile
            cdo fldmean ${outdir}/$outfile ${outdir}/$tmpfile
	    mv ${outdir}/$tmpfile ${outdir}/$outfile
            ncrename -v $var,${var}${reg} ${outdir}/$outfile	    
            std_name=$(ncdump -h $file | grep $var | grep standard_name | cut -f2 -d":")
            lng_name=$(ncdump -h $file | grep $var | grep long_name | cut -f2 -d":")
            ncatted -O -a standard_name,${std_name}${reg} ${outdir}/$outfile ${outdir}/$outfile
            ncatted -O -a long_name,${lng_name}_${reg} ${outdir}/$outfile ${outdir}/$outfile
          done #leadtime
         done #mb
      done #sd
    fi
  done #reg
done #var
