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

# This script intents to obtain a weighted average from some spatial variable
# in some specific regions (for the NEMO grid variables)

# cp $mask ${mask}.bkp
# ncrename -d latitude,lat -d longitude,lon $mask
# no se puede con esta mascara porque se rompe, asi que probar:
# ncdump $mask > mask.txt
# modificas a mano editando el mask.txt y lo vuelves a pasar a nc
# ncgen -b mask.txt -o mask.nc

module load CDO/1.7.2-foss-2015a

exp=i019 #i025
mask=/esnas/autosubmit/con_files/mask.regions.Ec2.3_O1L42.nc
for var in heatc0m-300m ; do # heatc0m-300m, sit, iiceheco
  for reg in TotalArc ; do #$( cdo showvar $mask )
    dir=/esnas/exp/ecearth/$exp/monthly_mean/${var}_f6h
    outdir=/esnas/exp/ecearth/$exp/monthly_mean/${var}${reg}_f6h
    mkdir -p $outdir
    if [[ $reg != "nav_lat" ]] && [[ $reg != "nav_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}_Omon_EC-EARTH_${exp}_${sd}_${mb}_${leadtime} # OImon for the ICE
            outfile=${var}${reg}_Omon_EC-EARTH_${exp}_${sd}_${mb}_${leadtime} #OImon 
	    tmpfile=${var}${reg}_Omon_EC-EARTH_${exp}_${sd}_${mb}_${leadtime}_tmp # OImon
	    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
