#!/bin/bash
module load nco/4.4.8

ia="1"    #=== Indices of chosen Amip  datasets (see below AMIP_VERSION_NAMES/AMIP_VERSION_FOLDERS)
io="1"    #=== Indices of chosen Ozone datasets (see below OZON_VERSION_NAMES/OZON_VERSION_FOLDERS)

#===============================================================================
#=== 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 ===============================
#===============================================================================
local=$PWD
case $machine in
  ada)    work=$WORKDIR;    DATAIN=""
          DATAOU='/workgpfs/rech/psl/rpsl035/IGCM' ;;
  curie)  work=$CCCWORKDIR; DATAIN=""
          DATAOU='/ccc/work/rech/psl/rpsl035/IGCM' ;;
  ciclad) work=/data/$USER; DATAIN=/prodigfs/project/input4MIPs/CMIP6/CMIP
          DATAOU='/prodigfs/ipslfs/igcmg/IGCM'     ;;
esac
DATAOU=/home/tlurton/IGCM     ##### !!!!!! PROVISOIRE !!!!!!!

#--- INPUT DATA: AMIP
AMIP_VERSION_NAMES=('PCMDI-AMIP-1-1-3')
AMIP_VERSION_FOLDERS=('gn/v20161031')
AMIP_FOLDER_IN=$DATAIN'/PCMDI/${amip_version_name}/${W}/mon/${V}/${amip_version_folder}'
amip_tname_in=('ocean' 'seaIce')
amip_vname_in=('tos' 'siconc')
amip_fname_in='${V}_input4MIPs_SSTsAndSeaIce_CMIP_${amip_version_name}_${amip_version_folder%/*}_187001-20????.nc'

#--- INPUT DATA: OZONE
OZON_VERSION_NAMES=('UReading-CCMI-1-0')
OZON_VERSION_FOLDERS=('gn/v20160711')
OZON_VERSION_FOLDERS_CLIM=('gn/v20160830')
OZON_FOLDER_IN=$DATAIN/'UReading/${ozon_version_name}/atmos/mon${clim}/${V}/${ozon_version_folder}'
ozon_vname_in='vmro3'
ozon_fname_in='${V}_input4MIPs_ozone_CMIP_${ozon_version_name}_${ozon_version_folder%/*}_${Yi}01-${Yf}12.nc'

#--- VERSIONS OF INPUT FILES EFFECTIVELY CHOSEN
((ia--)); ((io--))

#--- OUTPUT DATA
DATAOU=${DATAOU%/*}/ANTICHAMBRE; if [ ! -d $DATAOU ]; then mkdir -p $DATAOU; fi
AMIP_FOLDER_OU=$DATAOU/'ATM/LIMIT/AMIP.${amip_version_folder##*/}/${suf}'
OZON_FOLDER_OU=$DATAOU/'ATM/OZONE/UReading.${ozon_version_folder##*/}'
amip_vname_ou=('tosbcs' 'sicbcs'); amip_fname_ou='amip${bc}_${V}_360x180_${Y}.nc'
ozon_vname_ou='tro3'             ; ozon_fname_ou='${V}_${Y}.nc'
Y_amip_beg=1870 ; Y_amip_end=2017    #--- FOR AMIP  FILES (INTERANNUAL)
Y_ozon_beg=1850 ; Y_ozon_end=2014    #--- FOR OZONE FILES (INTERANNUAL)
Y_clim_beg=1979 ; Y_clim_end=2008    #--- FOR CLIMATOLOGIES (COMMON PERIOD FOR O3 AND SIC/SST)
Y_pind_beg=1870 ; Y_pind_end=1899    #--- FOR SST/SIC PRE-INDUSTRIAL CLIMATOLOGY
# NB: CLIMATOLOGIES ARE PRODUCED FOR EACH FILE CONTAINING "-clim" SUFFIX FOUND IN THE FOLDER TREE, IN PARTICULAR FOR OZONE.

#--- RECOMPUTE FILES THAT ARE ALREADY PRESENT (y/n)
recomp='n'
do_amip='n'
do_ozon='y'

if [ "$do_amip" = "y" ]; then
  amip_version_name=${AMIP_VERSION_NAMES[$ia]}; amip_version_folder=${AMIP_VERSION_FOLDERS[$ia]}
  echo ">> Chosen SST files:   $(V=${amip_vname_in[0]}; amip_version_name=$amip_version_name; amip_version_folder=$amip_version_folder; eval echo $AMIP_FOLDER_IN)"
  echo ">> Chosen SIC files:   $(V=${amip_vname_in[1]}; amip_version_name=$amip_version_name; amip_version_folder=$amip_version_folder; eval echo $AMIP_FOLDER_IN)"
fi
if [ "$do_ozon" = "y" ]; then
  ozon_version_name=${OZON_VERSION_NAMES[$io]}; ozon_version_folder=${OZON_VERSION_FOLDERS[$io]}
  echo ">> Chosen OZONE files: $(V=${ozon_vname_in};    ozon_version_name=$ozon_version_name; ozon_version_folder=$ozon_version_folder; eval echo $OZON_FOLDER_IN)"
fi

#==================================================================================
function addc {
  local s
  s="$1"; while [ ${#s} -lt $2 ]; do s="_$s"; done ; echo "$s"; unset s
}
#==================================================================================
function progress_bar {
# $1: iteration  $2: iterations number  $3: length of the bar
  local n bar
  bar=`echo "scale=1 ; (100*$1)/$2" | bc`
  bar="`addc "$bar" 5`% ["
  n=`echo "scale=0 ; ($3*$1)/$2" | bc`
  if [ $n -ne 0 ]; then bar="$bar"`eval "printf '='%.0s {1..$n}"`; fi
  n=$(($3-$n))
  if [ $n -ne 0 ]; then bar="$bar"`eval "printf '.'%.0s {1..$n}"`']\r'; fi
  echo -ne $bar; if [ $2 -eq $1 ]; then echo; fi
  unset n bar
}
#==================================================================================
function extract {
# Input arguments:
#    $1: vin,vou       (input/output variable names)
#    $2: fin,fou       (input/output files names)
#    $3: Ymin,Ymax,ny  (min/max available years, years/file number)
#    $4: nmrg          (number of additional months before and after)
#
# Purpose:
#  * Extract year $Y for variable $v_in from files $f_in containing data from
#    $Ymin to $Ymax, where each input file contains $ny years (=0 for single file)
#  * Outputs are stored in file $fou, and variable renamed $vou. Special cases:
#  * Optionally, add before/after the 12 months the $nmrg previous/next months.
#    - Y=Ymin (missing Ymin-1) => $nmrg last  months of year $Y used instead.
#    - Y=Ymax (missing Ymax+1) => $nmrg first months of year $Y used instead.
#
# Remark:  First record of first file has to be january $Yb.
#
  local v_in v_ou d_in f_ou Ymin Ymax Yi Yf Y ny nbm nmrg it fin fou fm ff fp ib ie
  v_in="${1%%,*}"; v_ou="${1#*,}"; shift
  f_in="${1%%,*}"; f_ou="${1#*,}"; shift
  Ymin="${1%%,*}"; Ymax="${1#*,}"; ny="${Ymax#*,}"; Ymax="${Ymax%%,*}"; shift
  Y=$1; shift; if [ $# -eq 1 ]; then nmrg=$1; else nmrg=0; fi
  ff=actu_${v_in}_${Y}.nc; fm=""; fp=""
  #--- INITIAL AND FINAL YEAR OF FILE CONTAINING CURRENT YEAR
  if [ $ny -eq 0 ]; then
    Yi=$Ymin; Yf=$Ymax
  else
    Yi=$((ny*(Y/ny))); Yf=$((Yi+ny-1)); Yf=$(($Yf>$Ymax?$Ymax:$Yf))
  fi
  nbm=$((12*(Yf-Yi+1)-1))                           #--- MONTHS NUMBER OF CURRENT FILE
  it=$((12*(Y-Yi)))                                 #--- JANUARY INDEX IN CURRENT FILE
  fin=`V=$v_in; Yi=$Yi; Yf=$Yf; eval echo $f_in`    #--- CURRENT FILE NAME
  fou=`V=$v_ou; Y=$Y; eval echo $f_ou`              #--- OUTPUT FILE NAME
  ib=$(($it<=nmrg?0:$((it-nmrg))))                  #--- INDEX OF FIRST USED MONTH
  ie=$(($((it+11+mrg))>=$nbm?$nbm:$((it+11+nmrg)))) #--- INDEX OF LAST USED MONTH
  rm -f $ff ; rm -f $ff ; ncks -d time,$ib,$ie $fin $ff
  #--- MISSING PREVIOUS YEAR LAST  MONTHS => CURRENT YEAR INSTEAD
  if [ $it           -lt $nmrg ]; then fm="prev_${v_in}_${Y}.nc"; rm -f $fm
    if [[ $Y -eq $Ymin || $ny -eq 0  ]]; then ncks -d time,$((it-nmrg+12)),11 $fin $fm
    else Yi=$((ny*((Y-1)/ny))); Yf=$((Yi+ny-1)); Yf=$(($Yf>$Ymax?$Ymax:$Yf))
      ncks -d time,$((12*(Yf-Yi+1)-nmrg+it)),$((12*(Yf-Yi+1)-1)) `V=$v_in; Yi=$Yi; Yf=$Yf; eval echo $f_in` $fm
    fi
  fi
  #--- MISSING FOLLOWING YEAR FIRST MONTHS => CURRENT YEAR INSTEAD
  if [ $((it+nmrg+11)) -gt $nbm ]; then fp="next_${v_in}_${Y}.nc"; rm -f $fp
    if [[ $Y -eq $Ymax || $ny -eq 0  ]]; then ncks -d time,$((nbm-11)),$((it+nmrg-1)) $fin $fp
    else Yi=$((ny*((Y+1)/ny))); Yf=$((Yi+ny-1)); Yf=$(($Yf>$Ymax?$Ymax:$Yf))
      ncks -d time,0,$((nmrg-1)) `V=$v_in; Yi=$Yi; Yf=$Yf; eval echo $f_in` $fp
    fi
  fi
  if [ ! -d ${fou%/*} ]; then mkdir -p ${fou%/*}; fi
  if [[ "$fm" != "" || "$fp" != "" ]]; then
    rm -f $fou ; ncrcat $fm $ff $fp $fou ; rm -f $fm $ff $fp
  else
    mv $ff $fou
  fi
  if [ "$v_in" != "$v_ou" ]; then
    ncrename -v $v_in,$v_ou $fou > /dev/null 2>&1
  fi
}
#==================================================================================
function make_clim {
# Input arguments:
#    $1: variable name   $2: input files name
#    $3: beg,end years   $4: index for january (optional, starting from 0)
#
# Purpose:
#    Create a 12 months climatology for a variable using 1-year monthly files.
#
# Remark:
#    Files with additional months are usable if the index for january is given (default: 0)
#
  local f_ou f0 Yb Ye ib ie M MM
  Yb="${3%%,*}"; Ye="${3#*,}"
  if [ $# -eq 4 ]; then ib=$4; else ib=0; fi; ie=$((ib+11))  #=== INDEX $ib FOR JANUARY
  for M in $(eval echo {$ib..$ie}); do
    MM=$((M+1-ib)); if [ $MM -le 9 ]; then MM=0$MM; fi
    for Y in `eval echo {${Yb}..${Ye}}`; do
      f_ou=$(V=$1; Y=$Y; eval echo $2)
      rm -f ${1}_$Y$MM.nc ; ncks -d time,$M $(V=$1; Y=$Y; eval echo $f_ou) ${1}_$Y$MM.nc
    done
    rm -f ${1}_$MM.nc ; ncra ${1}_????$MM.nc ${1}_$MM.nc ; rm -f ${1}_????$MM.nc
    progress_bar $((M+1-ib)) $((ie-ib+1)) 50
  done
  f_ou=$(V=$1; Y=${Yb}_${Ye}_clim; eval echo $2); f_ou=$(V=$1; Y=${Yb}_${Ye}_clim; eval echo $f_ou)
  rm -f $f_ou ; ncrcat ${1}_??.nc $f_ou ; rm -f ${1}_??.nc
  f0=`V=$1; Y='YYYY'; eval echo $2`; f0=$(V=$1; Y='YYYY'; eval echo $f0); f0=${f0##*/}
  ncatted -a comment,global,a,c,"\nClimatology from $Yb to $Ye using file(s) $f0" $f_ou
  echo ">> Done for variable $1."
}
#==================================================================================
function str2ascii() {
  LC_CTYPE=C printf '%d' "'$1"
}

#==================================================================================
function deblank {
#--- REMOVE UNEXPECTED CHARACTERS (IN PARTICULAR THOSE WEIRD ASCII(0) CHARS)
  local a
  a=$1; while [ `str2ascii ${a:0:1}` -lt 32 ]; do a=${a:1:${#a}}; done; echo $a
}

#==================================================================================
function dim_nam {
  #--- GET DIMENSION $2 (X/Y/Z/T) NAME FOR FILE $1
  #--- SPECIAL CASE: RETURN 'Seasons' IF "$2" = "S".
  local a v Units
  case $2 in
    X) Units='degrees_east  degree_east  degree_e degrees_e "degrees east"  "degree east"  degreee degreese' ;;
    Y) Units='degrees_north degree_north degree_n degrees_n "degrees north" "degree north" degreen degreesn' ;;
    Z) Units='pa pascal pascals hpa millibar millibars mbar mbars mb bar bars atm atms atmosphere atmospheres' ;;
    T) Units=' since' ;;
    S) echo Seasons; return 0 ;;
    *) echo "error in dim_nam: unrecognized axis $2"; return 1 ;;
  esac
  for u in $Units; do
    case $2 in
      X|Y|Z) a=`ncdump -h $1 | grep -i ':units = "'"$u"'"'` ;;
      T)     a=`ncdump -h $1 | grep -i $u | grep ':units = "'` ;;
    esac
    if [ "$a" != "" ]; then
      if [ "$2" = "Z" ]; then v=${a%%:*}; v=`deblank $v`
        if [ "`ncdump -h $1 | grep -i "$v($v)"`" != "" ]; then break; fi
      else break
      fi
    fi
  done
  if [[ "$a" = "" && "$2" = "Z" ]]; then a=`ncdump -h $1 | grep -i ':positive = "'`; fi
  if [ "$a" = "" ]; then echo "error in dim_nam: unable to recognize axis $2"; return 1; fi
  echo ${a%%:*}; return 0
}

#==================================================================================
function test_var {
# Input arguments:
#    $1: file name  $2: variable name
  ncdump -h $1 | grep "double $2" > /dev/null; if [ $? -eq 0 ]; then return 0; fi
  ncdump -h $1 | grep "float  $2" > /dev/null; return $?
}
#==================================================================================
function renam_dims {
# Input arguments:
#    $1: file name  $2...: <axis>:<target_name> (axis=X,Y,Z or T)
#
# Purpose:
#    Rename dimensions, dimensional variables and possibly bounds_<variable>.
#
  local f=$1 out="" nam_in nam_ou
  shift
  while [ $# -ge 1 ]; do
    nam_ou=${1##*:}; nam_in=$(dim_nam $f ${1%:*}); shift
    if [ "$nam_in" != "$nam_ou" ]; then
      out="$out -d $nam_in,$nam_ou -v $nam_in,$nam_ou"
      nam_in=bounds_$nam_in; nam_ou=bounds_$nam_ou
      test_var $f $nam_in
      if [ $? -eq 0 ]; then out="$out -d $nam_in,$nam_ou -v $nam_in,$nam_ou"; fi
    fi
    ((ia++))
  done
  echo $out
}
#==================================================================================

tmp=tmp.$$.nc

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if [ "$do_amip" = "y" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#=== BUILD YEARLY INTERANNUAL SIC/SST FILES WITH 12 RECORDS
for is in $ia; do                                                            #--- Loop on Amip versions
  amip_version_name=${AMIP_VERSION_NAMES[$is]}
  amip_version_folder=${AMIP_VERSION_FOLDERS[$is]}
  for suf in AVE BCS; do                                                     #--- Loop on var type
    for ivar in $(eval echo {1..${#amip_vname_in[@]}}); do iv=$((ivar-1))    #--- Loop on variables

      #--- VARIABLES NAMES (INPUT, OUTPUT AND FOR FILE NAMING PURPOSE)
      v_in=${amip_vname_in[$iv]}; if [ "$suf" = "BCS" ]; then v_in=${v_in}bcs; fi
      v_ou=${amip_vname_ou[$iv]}; if [ "$suf" = "BCS" ]; then v_ou=${v_ou}bcs; fi
      var='sst';                  if [ $ivar  -eq  2  ]; then var='sic';       fi

      #--- INPUT/OUTPUT FOLDER NAME
      d_in=$(amip_version_name=$amip_version_name; amip_version_folder=$amip_version_folder; suf=$suf; V=$v_in; eval echo $AMIP_FOLDER_IN)
      d_ou=$(amip_version_name=$amip_version_name; amip_version_folder=$amip_version_folder; suf=$suf;          eval echo $AMIP_FOLDER_OU)
      if [ ! -d $d_ou ]; then mkdir -p $d_ou; fi

      #--- FILES NAMES (INPUT, OUTPUT)
      bc=""; if [ "$suf" = "BCS" ]; then bc=bc; fi
      f_in=$d_in/$(V=$v_in;               eval echo ${amip_fname_in})
      f_ou=$d_ou/$(V=$var; Y=\$Y; bc=$bc; eval echo ${amip_fname_ou})

      echo ">> BUILDING 12 MONTHS $v_in FILES FOR THE ${Y_amip_beg}-${Y_amip_end} PERIOD USING $amip_version_name DATASET (${amip_version_folder##*/})..."
      for Y in $(eval echo {${Y_amip_beg}..${Y_amip_end}}); do               #--- Loop on years

        #--- RECOMPUTE OR NOT
        if [[ -f $(Y=$Y; eval echo $f_ou) && $recomp = 'n' ]]; then continue; fi

        #--- 2D FIELDS EXTRACTION
        extract $v_in,$v_ou $AMIP_FOLDER_IN/$amip_fname_in,$f_ou $Y_amip_beg,$Y_amip_end,0 $Y 0

        progress_bar $((Y-Y_amip_beg+1)) $((Y_amip_end-Y_amip_beg+1)) 50
      done
    done
  done
done

#=== BUILD SIC/SST 12 RECORDS CLIMATOLOGIES
for is in $ia; do                                                            #--- Loop on Amip versions
  amip_version_name=${AMIP_VERSION_NAMES[$is]}
  amip_version_folder=${AMIP_VERSION_FOLDERS[$is]}
  for suf in AVE BCS; do                                                     #--- Loop on var type
    for ivar in $(eval echo {1..${#amip_vname_in[@]}}); do iv=$((ivar-1))    #--- Loop on variables

      #--- VARIABLES (OUTPUT, FOR FILE NAMING PURPOSE) AND OUTPUT FILE NAMES
      bc=""; if [ "$suf" = "BCS" ]; then bc=bc; fi
      v_ou=${amip_vname_ou[$iv]}; if [ "$suf" = "BCS" ]; then v_ou=${v_ou}bcs; fi
      var='sst';                  if [ $ivar  -eq  2  ]; then var='sic';       fi
      d_ou=$(amip_version_name=$amip_version_name; amip_version_folder=$amip_version_folder; suf=$suf; eval echo $AMIP_FOLDER_OU)
      f_ou=$(V=$var; Y=\$Y; bc=$bc; eval echo ${amip_fname_ou})

      for per in ${Y_clim_beg},${Y_clim_end} ${Y_pind_beg},${Y_pind_end}; do #--- Loop on periods
        echo ">> BUILDING 12 MONTHS $v_ou CLIMATOLOGIES ON PERIOD ${per%%,*}-${per##*,} for $suf DATA..."

        #--- RECOMPUTE OR NOT
        Yint=${per%%,*}_${per##*,}_clim
        if [[ -f $d_ou/$(Y=$Yint; eval echo $f_ou) && $recomp = 'n' ]]; then continue; fi

        #--- COMPUTE CLIMATOLOGY
        make_clim $v_ou $d_ou/$f_ou ${per} 0

      done
      cd $d_ou; ln -sf $(Y=2002; eval echo $f_ou) $(Y=2002_2002_clim; eval echo $f_ou); cd - 2>&1 > /dev/null
    done
  done
done
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
fi
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


coords="X:longitude Y:latitude Z:plev"

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if [ "$do_ozon" = "y" ]; then
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#=== BUILD YEARLY INTERANNUAL OZONE FILES WITH 12 RECORDS
for is in $io; do                                                 #--- Loop on Ozone versions
  ozon_version_name=${OZON_VERSION_NAMES[$is]}
  ozon_version_folder=${OZON_VERSION_FOLDERS[$is]}
  d_ou=$(ozon_version_name=$ozon_version_name; ozon_version_folder=$ozon_version_folder; eval echo $OZON_FOLDER_OU)               #--- Output folder
  if [ ! -d $d_ou ]; then mkdir -p $d_ou; fi
  v_ou=${ozon_vname_ou}                                           #--- Output variable
  v_in=${ozon_vname_in}                                           #--- Input  variable
  f_in=$(V=$v_in; Yi=\${Yi}; Yf=\${Yf}; ozon_version_name=$ozon_version_name; ozon_version_folder=$ozon_version_folder; eval echo $OZON_FOLDER_IN/${ozon_fname_in[$is]})
  f_ou=$(V=$v_ou; Y=\$Y; eval echo $ozon_fname_ou)

  nm=12
  d_o2=$d_ou/2D_12Fields                                          #--- Output folder (2D)
  d_o3=$d_ou/3D_12Fields                                          #--- Output folder (3D)
  if [ ! -d $d_o2 ]; then mkdir -p $d_o2; fi; f_o2=$d_o2/$f_ou
  if [ ! -d $d_o3 ]; then mkdir -p $d_o3; fi; f_o3=$d_o3/$f_ou

  echo ">> BUILDING $nm MONTHS OZONE FILES FOR PERIOD ${Y_ozon_beg}-${Y_ozon_end} USING $OZON_VERSION_NAMES DATASET (${ozon_version_folder##*/})..."
  for Y in $(eval echo {${Y_ozon_beg}..${Y_ozon_end}}); do      #--- Loop on years
 
    #--- RECOMPUTE OR NOT
    if [[ -f $(Y=$Y; eval echo $f_o3) && $recomp = 'n' ]]; then continue; fi

    #--- 3D FIELDS EXTRACTION
    extract $v_in,$v_ou $f_in,$f_o3 $Y_ozon_beg,$Y_ozon_end,50 $Y 0

    #--- RENAME DIMENSIONS ACCORDING TO $coords VARIABLE
    fo3=$(Y=$Y; eval echo $f_o3); fo2=$(Y=$Y; eval echo $f_o2)
    if [ $Y -eq $Y_ozon_beg ]; then args_ren=$(renam_dims $fo3 $coords); fi
    if [ "$args_ren" != "" ]; then ncrename $args_ren $fo3 2>&1 > /dev/null ; fi

    #--- ZONAL MEAN
    ncwa    -a longitude $fo3 $tmp ; mv $tmp $fo2
    ncks -x -v longitude $fo2 $tmp ; mv $tmp $fo2

    #--- REMOVE USELESS VARIABLE
    v="bounds_longitude"; test_var $fo2 $v
    if [ $? -eq 0 ]; then ncks -x -v $v $fo2 $tmp ; mv $tmp $fo2; fi

    progress_bar $((Y-Y_ozon_beg+1)) $((Y_ozon_end-Y_ozon_beg+1)) 50

  done
done

#=== BUILD OZONE 12 RECORDS CLIMATOLOGIES
for is in $io; do                                                 #--- Loop on Ozone versions
  ozon_version_name=${OZON_VERSION_NAMES[$is]}
  ozon_version_folder=${OZON_VERSION_FOLDERS[$is]}
  v_ou=${ozon_vname_ou}                                           #--- Output variable

  for rank in 3 2; do                                             #--- Loop on rank
    d12=$d_ou/${rank}D_12Fields

    #--- CLIMATOLOGY ON GIVEN YEARS INTERVAL (Y_clim_beg-Y_clim_end)
    f_ou=$(V=$v_ou; Y=${Y_clim_beg}_${Y_clim_end}_clim; eval echo $ozon_fname_ou) #--- Regular climatology name
    if [[ ! -f $d12/$f_ou || $recomp = 'y' ]]; then
      echo ">> BUILDING 12 MONTHS ${rank}D $v_ou CLIMATOLOGY ON PERIOD ${Y_clim_beg}-${Y_clim_end}..."
      make_clim $v_ou $d12/\$ozon_fname_ou ${Y_clim_beg},${Y_clim_end} 0
    fi

    #--- PRE-INDUSTRIAL CLIMATOLOGY USING SPECIAL FILE
    ozon_version_folder=$(eval echo ${OZON_VERSION_FOLDERS_CLIM[$is]})

    f_in=$(V=$v_in; Yi=1850; Yf=1850; ozon_version_name=$ozon_version_name; ozon_version_folder=$ozon_version_folder; clim='C'; eval echo $OZON_FOLDER_IN/$ozon_fname_in); #f_in=${f_in%.nc*}-clim.nc
    f_ou=$(V=$v_ou; Y=1850_1850_clim; eval echo $ozon_fname_ou)
    if [[ ! -f $d12/$f_ou || $recomp = 'y' ]]; then
      echo ">> BUILDING 12 MONTHS ${rank}D $v_ou PRE-INDUSTRIAL CLIMATOLOGY..."
      if [ $rank -eq 3 ]; then f_ou0=$d12/$f_ou

        #--- DUPLICATE FILE AND RENAME DIMENSIONS
        cp $f_in $d12/$f_ou ; args_ren=$(renam_dims $d12/$f_ou $coords)
        ncrename $args_ren -v $ozon_vname_in,$ozon_vname_ou $d12/$f_ou 2>&1 > /dev/null

      else
        #--- ZONAL MEAN
        ncwa    -a longitude      $f_ou0 $tmp ; mv $tmp $d12/$f_ou
        ncks -x -v longitude $d12/$f_ou  $tmp ; mv $tmp $d12/$f_ou

        #--- REMOVE USELESS VARIABLE
        v="bounds_longitude"
        test_var $d12/$f_ou $v
        if [ $? -eq 0 ]; then ncks -x -v $v $d12/$f_ou $tmp ; mv $tmp $d12/$f_ou; fi
      fi
    fi
  done
done

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
fi
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

