Index: /TOOLS/CMIP6_FORCING/OZONE/clims_CMIP6.bash
===================================================================
--- /TOOLS/CMIP6_FORCING/OZONE/clims_CMIP6.bash	(revision 3846)
+++ /TOOLS/CMIP6_FORCING/OZONE/clims_CMIP6.bash	(revision 3847)
@@ -2,6 +2,8 @@
 module load nco/4.6.9
 
-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)
+#=== Indices of chosen datasets among available collection (see DATANAMES after)
+DOPROCESS=('y' 'y')          #--- PROCESSED DATA TYPES (SSTandSeaIce, ozone)
+IXPROCESS=("0" "3")        #--- PROCESSED DATASETS INDICES
+recomp='n'                   #--- RECOMPUTE FILES THAT ARE ALREADY PRESENT (y/n)
 
 #===============================================================================
@@ -17,5 +19,4 @@
 #=== PARAMETERS NOT SUPPOSED TO BE CHANGED OFTEN ===============================
 #===============================================================================
-local=$PWD
 case $machine in
   ada)    work=$WORKDIR
@@ -26,439 +27,138 @@
           DATAOU='/ccc/work/cont003/igcmg/igcmg/IGCM/ATM' ;;
   ciclad) work=/data/$USER
-          DATAIN='/prodigfs/project/input4MIPs/CMIP6/CMIP'
+          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
-#--- 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'
-res3D='144x96x66'
-res2D='96x66_zonal'
+#--- 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/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-stratO3-1-0/atmos/mon/\${var}/gn/v20170814/$f \
+           input4MIPs/CMIP6/DAMIP/CCCma/CCMI-hist-volc-1-0/atmos/mon/\${var}/gn/v20180503/$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 AUTOMATICALLY 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 FOR ce0l
+
+#==================================================================================
+#=== FEW FUNCTIONS
+#   NOTE: These functions are not specific to this script.
+#   EXCEPTION: in get_date (error in ciclad storage tree for PCMDI-AMIP-1-1-0):
+#          if [ $dataset = "PCMDI-AMIP-1-1-0" ]; then grid='gs1x1'; fi
+#==================================================================================
+source tools.bash
 
 
-#--- VERSIONS OF INPUT FILES EFFECTIVELY CHOSEN
-((ia--)); ((io--))
-
-#--- OUTPUT DATA
-if [ ! -d $DATAOU ]; then mkdir -p $DATAOU; fi
-AMIP_FOLDER_OU=$DATAOU/'LIMIT/AMIP.${amip_version_folder##*/}/${suf}'
-OZON_FOLDER_OU=$DATAOU/'OZONE/UReading/historical.${ozon_version_folder##*/}/original'
-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
+#=== 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 $fin); date=($DATADATES[$i]); fin=($fin)
+  if [ ${DOPROCESS[$i]} != 'y' ]; then continue; fi
+  echo ">> Chosen $dt:"
+  for ka in ${IXPROCESS[$i]}; do echo "  * ${fin[$ka]%/*} (${date[$ka]%-*})"; done
+done
 
 #==================================================================================
-function addc {
-  local s
-  s="$1"; while [ ${#s} -lt $2 ]; do s="_$s"; done ; echo "$s"; unset s
-}
+for i in $(eval echo {0..$((${#DATATYPES[@]}-1))}); do     #=== LOOP ON DATASETS
 #==================================================================================
-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
+  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                       #--- Parse input directory
+    gridin=$grid; if [ $dataset = "PCMDI-AMIP-1-1-0" ]; then gridin='gs1x1'; fi
+    dso=$dataset                                           #--- For naming purpose
+    case $dt in                                            #--- NAMING EXCEPTIONS
+      ozone) if [ "$dataset" =    "PCMDI-AMIP-1-0" ]; then dso='AMIP'; fi ;;
+      SSTAndSeaIce) dso=${dso#*hist-}; dso=hist-${dso%%-*}
+             if [ "$dataset" = "UReading-CCMI-1-0" ]; then dso="historical"; fi ;;
+    esac
+    #==============================================================================
+    for iv in $(eval echo {0..$((${#vin[@]}-1))}); do      #--- Loop on variables
+    #==============================================================================
+      da=${date[$is]}; Yb=${da%%-*}; Ye=${da#*-}; dY=${Ye##*-}; Ye=${Ye%-*}
+      v_in=${vin[$iv]}; v_ou=${vou[$iv]}                   #--- Variables names
+      f_in=$(var=$v_in; Yb=\${Yb}; Ye=\${Ye}; datatype=$dt; grid=$gridin; eval echo $DATAIN/${fin[$is]})
+      axis=$(get_grid $(Yb=$Yb; Ye=????; eval echo $f_in) $v_in)
+      res=${axis#*=}; axis=${axis%=*}
+      doZon='n'; if [ $axis = 'XYZT' ]; then doZon='y'; fi #--- Zonal mean ?  For 3D files
+      if [ $doZon = 'y' ]; then                            #--- 2 directories for 3D files
+        res3D=${res%x*}; res2D=${res3D#*x}_zonal; f_ou=${f_ou%/*}/\\\${res}/${f_ou##*/}
+      fi
+      f_ou=$(var=${vfo[$iv]}; Y=\${Y}; dataset=$dso; eval echo $DATAOU/${fou})
+      echo ">> BUILDING 12 MONTHS ${v_in} FILES FOR THE $Yb-$Ye PERIOD USING $dataset DATASET ($version)..."
+      #============================================================================
+      for Y in $(eval echo {$Yb..$Ye}); do                 #--- Loop on years
+      #============================================================================
+        fO=$(Y=$Y; res=${res3D}; eval echo ${f_ou})        #--- Original resolution
+        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 [ $doZon = '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-Yb+1)) $((Ye-Yb+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]}
+
+        #=== 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=$Yc; res=${res3D}; eval echo ${f_ou})       #--- Original resolution
+        if [[ ! -f $fO || $recomp = 'y' ]]; then
+          if [ "$c" = "y" ]; then
+            echo ">> BUILDING $v_ou CLIMATOLOGY USING SPECIAL FILE ${fC0##*/} ($version)..."
+            cp $fC0 $fO ; rename_dims $fO $coords          #--- Rename dims/atts
+          else
+            echo ">> BUILDING $v_ou CLIMATOLOGY USING YEARLY FILES FOR $per ($version)..."
+            make_clim ${v_ou} $f_ou $per 0                 #--- Compute climatology
+          fi
+        fi
+        if [ $doZon = 'y' ]; then
+          fZ=$(Y=$Y; res=${res2D}; eval echo ${f_ou})      #--- Zonal File name
+          if [[ ! -f $fZ || $recomp = 'y' ]]; then zonal_mean $fO $fZ; fi
+        fi
+      done
+      #============================================================================
     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 get_boundsvar {
-# Input arguments:
-#    $1: file name  $2: variable name
-  local a=$(ncdump -h $1 | grep -P "\t$2:bounds")
-  if [ "$a" != "${a#*\"}" ]; then a=${a#*\"}; echo ${a%\"*}; else echo ""; fi
-}
-#==================================================================================
-function rename_bounds {
-# Input arguments:
-#    $1: file name  $2: variable name  $3: new variable name
-  local vin=$(get_boundsvar $1 $2) beg end vou
-  if [ "$vin" = "" ]; then return 1; fi
-  beg=${vin##*$2}; if [ "$beg" = "$vin" ]; then beg=$vin; fi
-  beg=${vin%%$2*}; if [ "$end" = "$vin" ]; then end=$vin; fi
-  if [[  "$beg" = ""  &&  "$end" = ""  ]]; then return 1; fi
-  vou=$beg$3$end
-  echo "$2,$vin,$vou"
-}
-#==================================================================================
-function renam_dims {
-# Input arguments:
-#    $1: file name  $2...: <axis>:<target_name> (axis=X,Y,Z or T)
-#
-# Purpose:
-#    Rename dimensions, dimensional variables.
-#    In case of boundary grid variables with bounds_<variable> names are available,
-#    they are renamed together with the corresponding "bounds" attributes.
-  local vio 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"
-      #--- CHECK WETHER "bounds" ATTRIBUTE IS THERE
-      vio="$(rename_bounds $f $nam_in $nam_ou)"
-      if [ "$vio" != "" ]; then out="-a bounds,${vio%%,*},m,c,${vio##*,} ${out} -v ${vio#*,}"; fi
-    fi
-    ((ia++))
-  done
-  echo $out
-}
+  #================================================================================
+done
 #==================================================================================
 
-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/${res2D}                                             #--- Output folder (2D)
-  d_o3=$d_ou/${res3D}                                             #--- 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 DIMS/VARS ACCORDING TO $coords VARIABLE + "bounds" ATTRIBUTE IF REQUIRED
-    fo3=$(Y=$Y; eval echo $f_o3); fo2=$(Y=$Y; eval echo $f_o2)
-    if [ $Y -eq $Y_ozon_beg ]; then
-      args_all=$(renam_dims $fo3 $coords)
-      args_att=${args_all%|*}; args_ren=${args_all#*|}
-    fi
-    if [ "$args_att" != "" ]; then ncatted  $args_att $fo3 2>&1 > /dev/null ; 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 res in ${res3D} ${res2D}; do                                #--- zonal/3D loop
-    dr=$d_ou/$res
-
-    #--- 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 $dr/$f_ou || $recomp = 'y' ]]; then
-      echo ">> BUILDING 12 MONTHS $res $v_ou CLIMATOLOGY ON PERIOD ${Y_clim_beg}-${Y_clim_end}..."
-      make_clim $v_ou $dr/\$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 $dr/$f_ou || $recomp = 'y' ]]; then
-      echo ">> BUILDING 12 MONTHS $res $v_ou PRE-INDUSTRIAL CLIMATOLOGY..."
-      if [ "$res" = "${res3D}" ]; then f_ou0=$dr/$f_ou
-
-        #--- DUPLICATE FILE AND RENAME DIMENSIONS
-        cp $f_in $dr/$f_ou
-        args_all=$(renam_dims $dr/$f_ou $coords)
-        args_att=${args_all%|*}; args_ren=" -v $ozon_vname_in,$ozon_vname_ou ${args_all#*|}"
-        if [ "$args_att" != "" ]; then ncatted  $args_att $dr/$f_ou 2>&1 > /dev/null ; fi
-        if [ "$args_ren" != "" ]; then ncrename $args_ren $dr/$f_ou 2>&1 > /dev/null ; fi
-      else
-        #--- ZONAL MEAN
-        ncwa    -a longitude     $f_ou0 $tmp ; mv $tmp $dr/$f_ou
-        ncks -x -v longitude $dr/$f_ou  $tmp ; mv $tmp $dr/$f_ou
-
-        #--- REMOVE USELESS VARIABLE
-        v="bounds_longitude"
-        test_var $dr/$f_ou $v
-        if [ $? -eq 0 ]; then ncks -x -v $v $dr/$f_ou $tmp ; mv $tmp $dr/$f_ou; fi
-      fi
-    fi
-  done
-done
-
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-fi
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-
Index: /TOOLS/CMIP6_FORCING/OZONE/tools.bash
===================================================================
--- /TOOLS/CMIP6_FORCING/OZONE/tools.bash	(revision 3847)
+++ /TOOLS/CMIP6_FORCING/OZONE/tools.bash	(revision 3847)
@@ -0,0 +1,274 @@
+function parse_dir {
+# Syntax: export variables from directory $1 with structure var1/var2/.../varN ($2)
+# Each variable ${vari} is exported.
+  local d=$1 s=$2
+  while :; do
+    export ${s%%/*}=${d%%/*}
+    s=${s#*/}; d=${d#*/}
+    if [ "$s" = "${s#*/}" ]; then break; fi
+  done
+}
+#==================================================================================
+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: v_in,v_ou     (input/output variable names)
+#    $2: f_in,f_ou     (input/output files names)
+#    $3: Ymin,Ymax,dY  (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 $dY years
+#  * Outputs are stored in file $f_ou, and variable renamed $v_ou.
+#  * 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 $Ymin.
+#
+  local v_in v_ou d_in f_ou Ymin Ymax Yb Ye Y dY 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#*,}"; dY="${Ymax#*,}"; Ymax="${Ymax%%,*}"; shift
+  Y=$1; shift; if [ $# -eq 1 ]; then nmrg=$1; else nmrg=0; fi
+  if [ $dY -eq $((Ymax-Ymin+1)) ]; then dY=0; fi    #--- SINGLE FILE
+  ff=actu_${v_in}_${Y}.nc; fm=""; fp=""
+  #--- INITIAL AND FINAL YEAR OF FILE CONTAINING CURRENT YEAR
+  if [ $dY -eq 0 ]; then
+    Yb=$Ymin; Ye=$Ymax
+  else
+    Yb=$((dY*(Y/dY))); Ye=$((Yb+dY-1)); Ye=$(($Ye>$Ymax?$Ymax:$Ye))
+  fi
+  nbm=$((12*(Ye-Yb+1)-1))                           #--- MONTHS NUMBER OF CURRENT FILE
+  it=$((12*(Y-Yb)))                                 #--- JANUARY INDEX IN CURRENT FILE
+  fin=`var=$v_in; Yb=$Yb; Ye=$Ye; eval echo $f_in`  #--- CURRENT FILE NAME
+  fou=`var=$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 MONTHF
+  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 || $dY -eq 0  ]]; then ncks -d time,$((it-nmrg+12)),11 $fin $fm
+    else Yb=$((dY*((Y-1)/dY))); Ye=$((Yb+dY-1)); Ye=$(($Ye>$Ymax?$Ymax:$Ye))
+      ncks -d time,$((12*(Ye-Yb+1)-nmrg+it)),$((12*(Ye-Yb+1)-1)) `var=$v_in; Yb=$Yb; Ye=$Ye; 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 || $dY -eq 0  ]]; then ncks -d time,$((nbm-11)),$((it+nmrg-1)) $fin $fp
+    else Yb=$((dY*((Y+1)/dY))); Ye=$((Yb+dY-1)); Ye=$(($Ye>$Ymax?$Ymax:$Ye))
+      ncks -d time,0,$((nmrg-1)) `var=$v_in; Yb=$Yb; Ye=$Ye; 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=$(var=$1; Y=$Y; eval echo $2)
+      rm -f ${1}_$Y$MM.nc ; ncks -d time,$M $(var=$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=$(var=$1; Y=${Yb}_${Ye}_clim; eval echo $2)
+  rm -f $f_ou ; ncrcat ${1}_??.nc $f_ou ; rm -f ${1}_??.nc
+  f0=`var=$1; Y='YYYY'; eval echo $2`; f0=$(var=$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 get_boundsvar {
+# Input arguments:
+#    $1: file name  $2: variable name
+  local a=$(ncdump -h $1 | grep -P "\t$2:bounds")
+  if [ "$a" != "${a#*\"}" ]; then a=${a#*\"}; echo ${a%\"*}; else echo ""; fi
+}
+#==================================================================================
+function rename_bounds {
+# Input arguments:
+#    $1: file name  $2: variable name  $3: new variable name
+#    returns: $old_var,$old_boundvar,$new_boundvar
+  local vin=$(get_boundsvar $1 $2) beg end vou
+  if [ "$vin" = "" ]; then return 1; fi
+  beg=${vin##*$2}; if [ "$beg" = "$vin" ]; then beg=$vin; fi
+  beg=${vin%%$2*}; if [ "$end" = "$vin" ]; then end=$vin; fi
+  if [[  "$beg" = ""  &&  "$end" = ""  ]]; then return 1; fi
+  vou=$beg$3$end
+  echo "$2,$vin,$vou"
+}
+#==================================================================================
+function rename_dims {
+# Input arguments:
+#    $1: file name  $2...: <axis>:<target_name> (axis=X,Y,Z or T)
+#
+# Purpose:
+#    Rename dimensions, dimensional variables.
+#    In case of boundary grid variables with bounds_<variable> names are available,
+#    they are renamed together with the corresponding "bounds" attributes.
+  local vio f=$1 att="" ren="" 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 
+      ren="$ren -d $nam_in,$nam_ou -v $nam_in,$nam_ou"
+      #--- CHECK WETHER "bounds" ATTRIBUTE IS THERE
+      vio="$(rename_bounds $f $nam_in $nam_ou)"
+      if [ "$vio" != "" ]; then
+        att="$att -a bounds,$nam_ou,m,c,${vio##*,}"; ren="$ren -v ${vio#*,}"
+      fi
+    fi
+  done
+  if [ "$ren" != "" ]; then ncrename $ren $f 2>&1 > /dev/null ; fi
+  if [ "$att" != "" ]; then ncatted  $att $f 2>&1 > /dev/null ; fi
+}
+#==================================================================================
+function zonal_mean {
+# Input arguments:
+#    $1: input file  $2: output file
+  local tmp=tmp.$$.nc
+  ncwa       -a longitude $1 $tmp ; mv $tmp $2    #--- Zonal mean
+  ncks -O -x -v longitude $2 $tmp ; mv $tmp $2    #--- Remove longitude
+  v="bounds_longitude"; test_var $2 $v            #--- Remove bounds vars
+  if [ $? -eq 0 ]; then ncks -O -x -v $v $2 $tmp ; mv $tmp $2; fi
+}
+#==================================================================================
+function get_date {
+# $1: varname  $2: datatype  $3: dirin  $4:...: files_in
+# Assumes the following filename structure: *_${Yb}*-${Ye}*.* (Yb/e: 4 digits)
+  local v_in dtyp d_in f_in ixf Yb Ye St a f first dates
+  v_in=$1; shift; dtyp=$1; shift; d_in=$1; shift
+  for f_in in $@; do parse_dir ${f_in} $DIRSTRUCT; Yb=1000000; Ye=0; first='t'
+    #=== /!\ ERROR IN THE STORAGE TREE ON CICLAD FOR PCMDI-AMIP-1-1-0
+    if [ $dataset = "PCMDI-AMIP-1-1-0" ]; then grid='gs1x1'; fi
+    for f in $(var=$v_in; Yb=????; Ye=????; datatype=$dtyp; eval echo $d_in/$f_in); do
+      a=${f##*_}; if [ ${a::4} -le $Yb ]; then Yb=${a::4}; fi
+      a=${a##*-}; if [ ${a::4} -ge $Ye ]; then Ye=${a::4}; fi
+      if [ $first = 't' ]; then St=$((Ye-Yb+1)); first='f'; fi
+    done
+    if [ $f_in = $1 ]; then dates="$Yb-$Ye-$St"; else dates="$dates $Yb-$Ye-$St"; fi
+  done
+  echo $dates
+}
+#==================================================================================
+function dim_len {
+  local n
+  if [ "$2" = "T" ]; then
+    n=$(ncdump -h $1 | grep 'UNLIMITED'); n=${n#*// (}; echo ${n% currently*}
+  else
+    n=$(ncdump -h $1 | grep $2' = '); n=${n#* = }; echo ${n% ;*}
+  fi
+}
+#==================================================================================
+function get_grid {
+  # $1: filename $2: varname
+  X=$(dim_nam $1 X); if [ $? -ne 0 ]; then X=""; else lX=$(dim_len $1 $X); fi
+  Y=$(dim_nam $1 Y); if [ $? -ne 0 ]; then Y=""; else lY=$(dim_len $1 $Y); fi
+  Z=$(dim_nam $1 Z); if [ $? -ne 0 ]; then Z=""; else lZ=$(dim_len $1 $Z); fi
+  T=$(dim_nam $1 T); if [ $? -ne 0 ]; then T=""; else lT=$(dim_len $1  T); fi
+  t=$(ncdump -h $1 | grep "double $2")
+  if [ $? -ne 0 ]; then t=$(ncdump -h $1 | grep "float $2"); fi
+  t=${t##*$2(}; t=${t%)*}; g=""; r=""
+  while :; do s=${t##*, }; t=${t%,*}
+    case $s in
+      $X) g=${g}X; r=${r}x$lX ;;
+      $Y) g=${g}Y; r=${r}x$lY ;;
+      $Z) g=${g}Z; r=${r}x$lZ ;;
+      $T) g=${g}T; r=${r}x$lT ;;
+    esac
+    if [ "$s" = "$t" ]; then break; fi
+  done
+  echo $g=${r:1:${#r}}
+}
+#==================================================================================
+
