#!/bin/bash
module load nco/4.6.9

#=== Indices of chosen datasets among available collection (see DATANAMES after)
DOPROCESS=('n' 'y')          #--- PROCESSED DATA TYPES (SSTandSeaIce, ozone)
IXPROCESS=("0" "5 6")        #--- PROCESSED DATASETS INDICES
recomp='n'                   #--- RECOMPUTE FILES THAT ARE ALREADY PRESENT (y/n)

#===============================================================================
#=== DETERMINE THE MACHINE NAME ================================================
#===============================================================================
if   [ ${HOSTNAME:0:3} = 'ada'    ]; then machine='ada';    work=$WORKDIR
elif [ ${HOSTNAME:0:5} = 'curie'  ]; then machine='curie';  work=$CCCWORKDIR
elif [ ${HOSTNAME:0:6} = 'ciclad' ]; then machine='ciclad'; work=/home/$USER/tmp
else echo "Not set up for this machine yet, sorry."; exit; fi
export machine=$machine

#===============================================================================
#=== PARAMETERS NOT SUPPOSED TO BE CHANGED OFTEN ===============================
#===============================================================================
case $machine in
  ada)    work=$WORKDIR
          DATAIN=""
          DATAOU='/workgpfs/rech/psl/rpsl035/IGCM/ATM'    ;;
  curie)  work=$WORKDIR
          DATAIN=""
          DATAOU='/ccc/work/cont003/igcmg/igcmg/IGCM/ATM' ;;
  ciclad) work=/data/$USER
          DATAIN='/prodigfs/project'
          DATAOU='/prodigfs/ipslfs/igcmg/IGCM/ATM'        ;;
esac
if [ "$DATAIN" = "" ]; then echo "Raw data folder for $machine has to be specified."; exit; fi
 DATAOU=/data/dcugnet$DATAOU  # No write acces to $DATAOU => temporary storage space.

#--- DATA TO TREAT (INTERANNUAL AND CLIMATOLOGIES): "SSTsAndSeaIce" "ozone":
DATATYPES=('SSTsAndSeaIce' 'ozone')
f='${var}_${datasets}_${datatype}_${project}_${dataset}_${grid}_${Yb}01-${Ye}??.nc'
FILES_IN=("input4MIPs/CMIP6/CMIP/PCMDI/PCMDI-AMIP-1-1-0/ocean/mon/\${var}/gn/v20160609/$f  \
           input4MIPs/CMIP6/CMIP/PCMDI/PCMDI-AMIP-1-1-1/ocean/mon/\${var}/gn/v20161020/$f  \
           input4MIPs/CMIP6/CMIP/PCMDI/PCMDI-AMIP-1-1-2/ocean/mon/\${var}/gn/v20170419/$f  \
           input4MIPs/CMIP6/CMIP/PCMDI/PCMDI-AMIP-1-1-3/ocean/mon/\${var}/gn/v20171031/$f  \
           input4MIPs/CMIP6/CMIP/PCMDI/PCMDI-AMIP-1-1-4/ocean/mon/\${var}/gn/v20180427/$f" \
          "input4MIPs/CMIP6/CMIP/UReading/UReading-CCMI-1-0/atmos/mon/\${var}/gn/v20160711/$f   \
           input4MIPs/CMIP6/ScenarioMIP/UReading/UReading-CCMI-ssp126-1-0/atmos/mon/\${var}/gn/v20181101/$f \
           input4MIPs/CMIP6/ScenarioMIP/UReading/UReading-CCMI-ssp245-1-0/atmos/mon/\${var}/gn/v20181101/$f \
           input4MIPs/CMIP6/ScenarioMIP/UReading/UReading-CCMI-ssp370-1-0/atmos/mon/\${var}/gn/v20181101/$f \
           input4MIPs/CMIP6/ScenarioMIP/UReading/UReading-CCMI-ssp585-1-0/atmos/mon/\${var}/gn/v20181101/$f \
           input4MIPs/CMIP6/ScenarioMIP/UReading/UReading-CCMI-ssp119-1-0/atmos/mon/\${var}/gn/v20190201/$f \
           input4MIPs/CMIP6/ScenarioMIP/UReading/UReading-CCMI-ssp534os-1-0/atmos/mon/\${var}/gn/v20190201/$f \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-stratO3-1-0/atmos/mon/\${var}/gn/v20170814/$f \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-nat-1-0/atmos/mon/\${var}/gn/v20180503/$f     \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-sol-1-0/atmos/mon/\${var}/gn/v20180503/$f     \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-volc-1-0/atmos/mon/\${var}/gn/v20180503/$f    \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-sol-1-1/atmos/mon/\${var}/gn/v20180525/$f     \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-nat-1-1/atmos/mon/\${var}/gn/v20180525/$f     \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-volc-1-1/atmos/mon/\${var}/gn/v20180525/$f    \
           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-ssp245-nat-1-0/atmos/mon/\${var}/gn/v20180820/$f")
CLIMS_IN=("/ / / / /" \
          "input4MIPs/CMIP6/CMIP/UReading/UReading-CCMI-1-0/atmos/monC/\${var}/gn/v20160830/$f  /  /  /  /  /  /  /")
VARNAM_IN=('tosbcs siconcbcs' 'vmro3')
DIRSTRUCT='datasets/exercise/project/origin/dataset/domain/frequency/var/grid/version/'
DATADATES=()                                #--- DETERMINED LATER

#--- RESULTS STORAGE
if [ ! -d $DATAOU ]; then mkdir -p $DATAOU; fi
FILES_OU=('LIMIT/AMIP.${version}/original/amipbcs_${var}_360x180_${Y}.nc' \
          'OZONE/${origin}/${dataset}.${version}/original/${var}_${Y}.nc')
#           SSTsAndSeaIce:        ozone:
VARNAM_OU=('tosbcs sicbcs'       'tro3')    #--- VARIABLES NAMES IN FILES
VARNAMFOU=('sst sic'             'tro3')    #--- VARIABLES NAMES FOR FILES NAMES
CLIMDATES=('1870-1899 1979-2008' '1850-1879 1979-2008')
coords="X:longitude Y:latitude Z:plev"      #--- COORDINATES NAMES KNOWN BY ce0l

#=== EXCEPTIONS FOR STORAGE TREE ERRORS: variables not deduced from folder name parsing
ex="PCMDI-AMIP-1-1-0:grid=gs1x1"  # <dset>:<var>=<val> if dataset=dset: export var=val

#==================================================================================
#=== FEW FUNCTIONS (not specific to this script)
#==================================================================================
source tools.bash

#=== DETERMINE TIME INTERVALS AND DISPLAY WHAT DATASET ARE ABOUT TO BE TREATED
for i in $(eval echo {0..$((${#DATATYPES[@]}-1))}); do
  fin=${FILES_IN[$i]}; dt=${DATATYPES[$i]}; var=${VARNAM_IN[$i]%% *}
  DATADATES[$i]=$(get_date $var $dt $DATAIN $DIRSTRUCT $fin $ex)
  date=(${DATADATES[$i]}); fin=($fin); if [ ${DOPROCESS[$i]} != 'y' ]; then continue; fi
  echo ">> Chosen $dt:"
  for ka in ${IXPROCESS[$i]}; do d=${date[$ka]}; dy=${d%%-*}; d=${d#*-}
    echo "  * ${fin[$ka]%/*} (${dy}-${d%%-*})"
  done
done

#==================================================================================
for i in $(eval echo {0..$((${#DATATYPES[@]}-1))}); do     #=== LOOP ON DATASETS
#==================================================================================
  if [ ${DOPROCESS[$i]} != 'y' ]; then continue; fi
     dt=${DATATYPES[$i]}                                   #=== SSTAndSeaIce, ozone...
    fin=(${FILES_IN[$i]}); vin=(${VARNAM_IN[$i]})          #===  INPUT FILE/VAR NAMES (each version)
     fou=${FILES_OU[$i]} ; vou=(${VARNAM_OU[$i]})          #=== OUTPUT FILE/VAR NAMES (single pair)
  date=(${DATADATES[$i]})                                  #=== ${Yb}-${Ye}-${dY}
   vfo=(${VARNAMFOU[$i]})                                  #=== VARNAME, FOR FILE NAMING
    cli=(${CLIMS_IN[$i]})                                  #=== SINGLE FILE CLIMATO
  #================================================================================
  for is in ${IXPROCESS[$i]}; do                           #=== LOOP ON VERSIONS
  #================================================================================
    parse_dir ${fin[$is]} $DIRSTRUCT $ex                   #--- Parse input directory
    dso=$(remove_version $dataset); dso=${dso#*-}          #--- For naming purpose
    case $dso in                                           #--- NAMING EXCEPTIONS
      "CCMI")          dso="historical"       ;;
      "CCMI-ssp534os") dso="CCMI-ssp534-over" ;;
    esac
    #==============================================================================
    for iv in $(eval echo {0..$((${#vin[@]}-1))}); do      #--- Loop on variables
    #==============================================================================
      da=${date[$is]}; Yi=${da%%-*}; Yf=${da#*-}; dYt=${Yf#*-}; Yf=${Yf%%-*}
      v_in=${vin[$iv]}; v_ou=${vou[$iv]}                   #--- Variables names
      f_in=$(var=$v_in; Yb=\${Yb}; Ye=\${Ye}; datatype=$dt; eval echo $DATAIN/${fin[$is]})
      axis=$(get_grid $(Yb=$Yi; Ye=????; eval echo $f_in) $v_in)
      res=${axis#*=}; axis=${axis%=*}
      Zonal='n'; if [ $axis = 'XYZT' ]; then Zonal='y'; fi #--- Zonal mean ?  For 3D files
      f_ou=$(var=${vfo[$iv]}; Y=\${Y}; dataset=$dso; eval echo $DATAOU/${fou})
      if [ $Zonal = 'y' ]; then                            #--- 2 directories for 3D files
        res3D=${res%x*}; res2D=${res3D#*x}_zonal; f_ou=${f_ou%/*}/\${res}/${f_ou##*/}
      fi
      echo ">> BUILDING 12 MONTHS ${v_in} FILES FOR THE $Yi-$Yf PERIOD USING $dataset DATASET ($version)..."
      Ye=$((Yi-1))
      #============================================================================
      for Y in $(eval echo {$Yi..$Yf}); do                 #--- Loop on years
      #============================================================================
        fO=$(Y=$Y; res=${res3D}; eval echo ${f_ou})        #--- Original resolution
        if [ $Y -eq $((Ye+1)) ]; then Yb=$Y; dY=${dYt%%-*}; Ye=$((Yb+dY-1)); dYt=${dYt#*-}; fi
        if [[ ! -f $fO || $recomp = 'y' ]]; then
          extract $v_in,$v_ou $f_in,$fO $Yb,$Ye,$dY $Y 0   #--- Field extraction
          rename_dims $fO $coords                          #--- Rename dims/atts
        fi
        if [ $Zonal = 'y' ]; then                          #--- Zonal mean
          fZ=$(Y=$Y; res=${res2D}; eval echo ${f_ou})      #--- Zonal File name
          if [[ ! -f $fZ || $recomp = 'y' ]]; then zonal_mean $fO $fZ; fi
        fi
        progress_bar $((Y-Yi+1)) $((Yf-Yi+1)) 50           #--- Check progress
      #============================================================================
      done
      #============================================================================
      for per in ${CLIMDATES[$i]}; do                      #--- Loop on periods
      #============================================================================
        Yb=${per%%-*}; Ye=${per##*-}; Yc=${Yb}_${Ye}_clim; c='n'; cli0=${cli[$is]}

        #=== Skip periods outside available years interval
        if [[ $Yb -lt ${da%%-*} || ${Yb} -gt ${da#*-} || $Yb -lt ${da%%-*} || ${Yb} -gt ${da#*-} ]]; then
          continue
        fi

        #=== Is there a single file climatology available ?
        fc0=$(var=$v_in; Yb=$Yb; Ye=$Yb; datatype=$dt; eval echo $DATAIN/${cli0})
        if [[ ${cli0} != "/" && -f $fc0 ]]; then c='y'; Yc=${Yb}_${Yb}_clim; fi

        fO=$(Y=\$Y; res=${res3D}; eval echo ${f_ou})       #--- Original resolution
        fOc=$(Y=$Yc; res=${res3D}; eval echo ${f_ou})      #--- ", target climatology
        if [[ ! -f $fOc || $recomp = 'y' ]]; then
          if [ "$c" = "y" ]; then
            echo ">> BUILDING $v_ou CLIMATOLOGY USING SPECIAL FILE ${fC0##*/} ($version)..."
            cp $fc0 $fOc ; rename_dims $fOc $coords        #--- Rename dims/atts
          else
            echo ">> BUILDING $v_ou CLIMATOLOGY USING YEARLY FILES FOR $per ($version)..."
            make_clim ${v_ou} $fO $per 0                   #--- Compute climatology
          fi
        fi
        if [ $Zonal = 'y' ]; then
          fZc=$(Y=$Yc; res=${res2D}; eval echo ${f_ou})    #--- Zonal File name
          if [[ ! -f $fZc || $recomp = 'y' ]]; then zonal_mean $fOc $fZc; fi
        fi
      done
      #============================================================================
    done
    #==============================================================================
  done
  #================================================================================
done
#==================================================================================


