#!/usr/bin/env bash
### ===========================================================================
###
### Creates grids.nc, masks.nc and areas.nc for OASIS-MCT
###
### ===========================================================================
##
##  Warning, to install, configure, run, use any of Olivier Marti's
##  software or to read the associated documentation you'll need at least
##  one (1) brain in a reasonably working order. Lack of this implement
##  will void any warranties (either express or implied).
##  O. Marti assumes no responsability for errors, omissions,
##  data loss, or any other consequences caused directly or indirectly by
##  the usage of his software by incorrectly or partially configured
##  personal.
##
###
### Documentation : https://forge.ipsl.jussieu.fr/igcmg/wiki/IPSLCM6/MOSAIX
###
## SVN information
#  $Author$
#  $Date$
#  $Revision$
#  $Id$
#  $HeadURL$

set +vx

echo ${Titre}"Starting CreateOasisGrids.bash"${Norm}

##
echo ${Titre}"Default configuration (may be overrided by command line parameters)"${Norm}
## ===========================================================================
OCE=ORCA2.3
# OCE=eORCA1.2
#ATM=ICO30
#ATM=ICO40
#ATM=ICO450
#ATM=LMD144142
ATM=LMD9695

## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================

echo ${Titre}"Defines computer"${Norm}
# ================
if [[ $(hostname) = curie* ]]    ; then arch=curie ; center=tgcc ; fi
if [[ $(hostname) = irene* ]]    ; then arch=irene ; center=tgcc ; fi
if [[ $(hostname) = lsce3005* ]] ; then arch=spip  ; center=spip ; fi

PROGRAM=$(basename ${0})

if [[ "X${R_IN}" = "X" ]] ; then
    
    case ${arch} in
	( irene )
	set +vx
	set +e
	TMPDIR=${CCCWORKDIR}/TMP
	SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
	PROGRAM=${BRIDGE_MSUB_REQNAME}
	MpiRun="time ccc_mprun"
	PyRun="time ccc_mprun -n 1" # Needed to force python to run on one process only
	#module purge
	source $(ccc_home -u igcmg)/MachineEnvironment/irene/env_irene
	source ${SUBMIT_DIR}/arch.env
	#module load nco
	module load python3 
	module load datadir/igcmg
	module list
	set -e
	;;
	( spip )
	R_IN=${HOME}/Scratch/IGCM
	TMPDIR=${HOME}/Scratch/TMP
	SUBMIT_DIR=$(pwd)
	MpiRun="/opt/local/bin/mpirun -n 4"
	PyRun="time"
	;; 
	( * ) exit -1 ;;
    esac
fi
##
echo ${Titre}"Command line parameters"${Norm}
## ===========================================================================
set -e
set -o verbose
set -o xtrace

while [[ ${1} = -* ]] ; do
    case ${1} in
	( -- ) shift ; break ;;
	( -o=* | --oce=*    ) OCE=${1##*=}     ; echo OCE:${OCE}    ;;
	( -o   | --oce      ) shift ; OCE=${1} ; echo OCE:${OCE}    ;;
	( -a=* | --atm=*    ) ATM=${1##*=}     ; echo ATM:${ATM}    ;;
	( -a   | --atm      ) shift ; ATM=${1} ; echo ATM:${ATM}    ;;
	( -v | --verbose    ) set -o verbose   ;;
	( -x | --xtrace     ) set -o xtrace    ;;
	( -e                ) set -e           ;;
	( -V | --noverbose  ) set +o verbose   ;;
	( -X | --noxtrace   ) set +o xtrace    ;;
	( -E                ) set +e           ;;
	( -* ) echo ${Bold}"Unknown option : ${1}"${Norm} ; return 1 ;;
    esac
    shift
done

##
echo ${Titre}"Short names (grid names in Oasis)"${Norm}
## ===========================================================================
case ${OCE} in
    ( *ORC*) oce=orc ;;
esac
case ${ATM} in
    ( *ICO*         ) atm=ico ;;
    ( *dynamico*    ) atm=ico ;;
    ( *lmd* | *LMD* ) atm=lmd ;;
esac

CplModel=${OCE}x${ATM}

##
echo ${Titre}"Get input files"${Norm}
## ===========================================================================
[[ -f ${OCE}_coordinates_mask.nc ]] || cp ${R_IN}/OCE/NEMO/${OCE}/${OCE}_coordinates_mask.nc  .
[[ -f ${ATM}_grid.nc             ]] || cp ${R_IN}/ATM/GRID/${ATM}_grid.nc                   .

#
echo ${Titre}"Format for OASIS-MCT files : should be NetCDF3 classic or NetCDF3 64 bits"${Norm}
# ---------------------------------------------------------------------------
FL_FMT=netcdf4
#
echo ${Titre}"Cleaning"${Norm}
# ----------------------------------------------------------------------------
rm -f grids_${CplModel}.nc masks_${CplModel}.nc areas_${CplModel}.nc
rm  -f *_tmp.nc

#
if [[ ${atm} = *lmd* ]] ; then
    ncrename --dimension lon,x  ${ATM}_grid_maskFrom_${OCE}.nc
    ncrename --dimension lat,y  ${ATM}_grid_maskFrom_${OCE}.nc
fi
#
#
echo ${Titre}"Creates ocean fields"${Norm}
# ----------------------------------------------------------------------------
for OCEGRID in T U V ; do
    ncks -C --history --append --variable nav_lon_grid_${OCEGRID},nav_lat_grid_${OCEGRID},bounds_lon_grid_${OCEGRID},bounds_lat_grid_${OCEGRID} ${OCE}_coordinates_mask.nc grids_${CplModel}.nc
    ncks -C --history --append --variable area_grid_${OCEGRID} ${OCE}_coordinates_mask.nc areas_${CplModel}.nc
    # Inverts mask values and switch to integer
    ncks --history -C --variable mask_${OCEGRID} ${OCE}_coordinates_mask.nc mask_${OCEGRID}_tmp.nc
    ncatted --history \
	    --attribute coordinates,mask_${OCEGRID},d,,         \
	    --attribute online_operation,mask_${OCEGRID},d,,    \
	    --attribute cell_measures,mask_${OCEGRID},d,,       \
    mask_${OCEGRID}_tmp.nc
    
    ncap2 --history --append --script "mask_${OCEGRID}=int(1-mask_${OCEGRID});"    mask_${OCEGRID}_tmp.nc masks_${CplModel}.nc
    rm mask_${OCEGRID}_tmp.nc
    ncatted --history \
	    --attribute long_name,mask_${OCEGRID},o,c,"Land-sea mask" \
	    --attribute units,mask_${OCEGRID},o,c,"Land:1, Ocean:0"    masks_${CplModel}.nc
    # Change order of dimensions
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncpdq --permute nvertex_grid_${OCEGRID},y_grid_${OCEGRID},x_grid_${OCEGRID} grids_${CplModel}_tmp.nc grids_${CplModel}.nc
    rm grids_${CplModel}_tmp.nc
done

ncks --history --append --variable lon,lat ${ATM}_grid_maskFrom_${OCE}.nc grids_${CplModel}.nc
 
#
echo ${Titre}"We need to have different names for dimensions and variables"${Norm}
# --------------------------------------------------------------------------------
ncrename --history --variable lon,alon   grids_${CplModel}.nc
ncrename --history --variable lat,alat   grids_${CplModel}.nc

if [[ ${ATM} = dynamico* || ${ATM} = ICO* ]] ; then 
    ncks --history --append --variable bounds_lon,bounds_lat ${ATM}_grid_maskFrom_${OCE}.nc grids_${CplModel}.nc
fi

ncks --history -C --append --variable aire   ${ATM}_grid_maskFrom_${OCE}.nc areas_${CplModel}.nc
ncatted --history --attribute coordinates,aire,d,,     \
	--attribute _FillValue,aire,d,,                \
	--attribute missing_value,aire,d,,             \
	--attribute online_operation,aire,d,,          \
	--attribute units,aire,o,c,"m2"                \
	--attribute standard_name,aire,o,c,"cell_area" \
	areas_${CplModel}.nc

ncks --history -C --variable OceMask,OceFrac,Oce2AtmMask ${ATM}_grid_maskFrom_${OCE}.nc OceMask_tmp.nc
ncatted --history \
	--attribute cell_methods,OceMask,d,c,       \
	--attribute coordinates,OceMask,d,,         \
	--attribute online_operation,OceMask,d,,    \
	--attribute _FillValue,OceMask,d,,          \
	--attribute missing_value,OceMask,d,,       \
        \
	--attribute cell_methods,OceFrac,d,c,       \
	--attribute coordinates,OceFrac,d,,         \
	--attribute online_operation,OceFrac,d,,    \
	--attribute _FillValue,OceFrac,d,,          \
	--attribute missing_value,OceFrac,d,,       \
        \
	--attribute cell_methods,Oce2AtmMask,d,c,       \
	--attribute coordinates,Oce2AtmMask,d,,         \
	--attribute online_operation,Oce2AtmMask,d,,    \
	--attribute _FillValue,Oce2AtmMask,d,,          \
	--attribute missing_value,Oce2AtmMask,d,,       \
	OceMask_tmp.nc

ncap2 --history --append --script "Oce2AtmMask=int(1-Oce2AtmMask)" OceMask_tmp.nc masks_${CplModel}.nc # For OASIS, ocean=0, land=1
rm OceMask_tmp.nc
ncatted --history \
	--attribute long_name,Oce2AtmMask,o,c,"Land-sea mask"   \
	--attribute units,OceMask,o,c,"Land:1, Ocean:0"  masks_${CplModel}.nc

ncatted --history --attribute history,global,d,, grids_${CplModel}.nc
ncatted --history --attribute history,global,d,, masks_${CplModel}.nc
ncatted --history --attribute history,global,d,, areas_${CplModel}.nc

if [[ ${atm} = *dynamico* || ${atm} = ico* ]] ; then
    ncrename --history --dimension cell,ycell grids_${CplModel}.nc
    ncrename --history --dimension cell,ycell areas_${CplModel}.nc
    ncrename --history --dimension cell,ycell masks_${CplModel}.nc
fi

#
if [[ ${atm} = dynamico* || ${atm} = ico* ]] ; then
    echo ${Titre}"DYNAMICO grids : 1) Set correct order of dimensions, 2) Add a dimension"${Norm}
    # -------------------------------------------------------------------------------------------
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncpdq --permute nvertex,ycell,xcell  grids_${CplModel}_tmp.nc grids_${CplModel}.nc

    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    cat <<EOF >add_dim.nco
//
defdim("xcell",1) ;
alat               [ycell,xcell] = alat       ;
alon               [ycell,xcell] = alon       ;
bounds_lat [nvertex,ycell,xcell] = bounds_lat ;
bounds_lon [nvertex,ycell,xcell] = bounds_lon ;
//
EOF
   
    ncap2 --history --append --script-file add_dim.nco  grids_${CplModel}_tmp.nc grids_${CplModel}.nc
    
    mv masks_${CplModel}.nc masks_${CplModel}_tmp.nc
    ncap2 --history --append --script 'defdim("xcell",1) '   masks_${CplModel}_tmp.nc masks_${CplModel}.nc
    mv masks_${CplModel}.nc masks_${CplModel}_tmp.nc
    ncap2 --history --append --script 'OceFrac    [ycell,xcell]=OceFrac'      masks_${CplModel}_tmp.nc masks_${CplModel}.nc
    ncap2 --history --append --script 'OceMask    [ycell,xcell]=OceMask'      masks_${CplModel}_tmp.nc masks_${CplModel}.nc
    ncap2 --history --append --script 'Oce2AtmMask[ycell,xcell]=Oce2AtmMask'  masks_${CplModel}_tmp.nc masks_${CplModel}.nc

    mv areas_${CplModel}.nc areas_${CplModel}_tmp.nc
    ncap2 --history --append --script 'defdim("xcell",1) ; aire[ycell,xcell]=aire ; ' areas_${CplModel}_tmp.nc areas_${CplModel}.nc

    rm -f grids_${CplModel}_tmp.nc areas_${CplModel}_tmp.nc masks_${CplModel}_tmp.nc
fi
 
#
echo ${Titre}"Some changes specific to LMDZ lon/lat grid"${Norm}
# ----------------------------------------------------------------------------
if [[ ${atm} = lmd* ]] ; then
    echo ${Titre}"Spreads lon and lat to get 2D fields"${Norm}
    # -----------------------------------------------------------------------
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncap2 --history --append --script "alon[y,x]=alon; alat[y,x]=alat"  grids_${CplModel}_tmp.nc grids_${CplModel}.nc
    rm -f grids_${CplModel}_tmp.nc
    ncatted --history \
	    --attribute long_name,alon,o,c,"Longitude"    \
	    --attribute long_name,alat,o,c,"Latitude"     \
	    --attribute units,alon,o,c,"degrees_east"     \
	    --attribute units,alat,o,c,"degrees_north"    \
	    --attribute grid_type,alon,o,c,"P"            \
	    --attribute grid_type,alat,o,c,"P"            \
	    --attribute overlap,alon,o,i,0                \
	    --attribute overlap,alat,o,i,0                grids_${CplModel}.nc
    
    echo ${Titre}"Generates cell corners"${Norm}
    # -----------------------------------------------------------------------
cat <<EOF > add_bounds.nco
defdim ("nvertex_lmd", 4) ;
*delta_x = alon(0,1) - alon(0,0) ;
*delta_y = alat(1,0) - alat(0,0) ;
//
bounds_lon[nvertex_lmd,y,x] = 0.0 ;
bounds_lat[nvertex_lmd,y,x] = 0.0 ;
//
bounds_lon (0,:,:) = alon + delta_x*0.5 ;
bounds_lat (0,:,:) = alat + delta_y*0.5 ;
bounds_lon (1,:,:) = alon + delta_x*0.5 ;
bounds_lat (1,:,:) = alat - delta_y*0.5 ;
bounds_lon (2,:,:) = alon - delta_x*0.5 ;
bounds_lat (2,:,:) = alat - delta_y*0.5 ;
bounds_lon (3,:,:) = alon - delta_x*0.5 ;
bounds_lat (3,:,:) = alat + delta_y*0.5 ;
//
where (bounds_lat >  90.0 ) bounds_lat =  90.0 ;;
where (bounds_lat < -90.0 ) bounds_lat = -90.0 ;;
//
EOF
    mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
    ncap2 --history --script-file add_bounds.nco -O grids_${CplModel}_tmp.nc grids_${CplModel}.nc
    rm grids_${CplModel}_tmp.nc
fi

#
 
echo ${Titre}"Generates grid o${atm}, 'o' meaning 'one'"${Norm}
# same as t${atm} grid, with surfaces set to 1
# and mask to 0 (ocean everywhere, to compute integral over the whole grid))
# This grid is used when field are quantities instead of fluxes (i.e river flow)
# ----------------------------------------------------------------------------
mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
ncap2 --history --script "o${atm}_lon=alon ; o${atm}_lat=alat ; bounds_o${atm}_lon=bounds_lon; bounds_o${atm}_lat=bounds_lat ; " grids_${CplModel}_tmp.nc grids_${CplModel}.nc

mv areas_${CplModel}.nc areas_${CplModel}_tmp.nc
ncap2 --history --script "o${atm}_aire=aire*0.0d+1.0d ; "   areas_${CplModel}_tmp.nc areas_${CplModel}.nc

mv masks_${CplModel}.nc masks_${CplModel}_tmp.nc
ncap2 --history --script "o${atm}_mask=int(Oce2AtmMask)*0+0 ; " masks_${CplModel}_tmp.nc masks_${CplModel}.nc

rm grids_${CplModel}_tmp.nc areas_${CplModel}_tmp.nc masks_${CplModel}_tmp.nc


echo ${Titre}"Generates grid c${atm}, 'o' meaning 'one'"${Norm}
# same as t${atm} grid, with surfaces set to grid area
# and mask to 0 (ocean everywhere, to compute integral over the whole grid))
# ----------------------------------------------------------------------------
mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
ncap2 --history --script "c${atm}_lon=alon ; c${atm}_lat=alat ; bounds_c${atm}_lon=bounds_lon ; bounds_c${atm}_lat=bounds_lat ; " grids_${CplModel}_tmp.nc grids_${CplModel}.nc

mv areas_${CplModel}.nc areas_${CplModel}_tmp.nc
ncap2 --history --script "c${atm}_aire=aire"   areas_${CplModel}_tmp.nc areas_${CplModel}.nc

mv masks_${CplModel}.nc masks_${CplModel}_tmp.nc
ncap2 --history --script "c${atm}_mask=int(Oce2AtmMask)*0+0 ; " masks_${CplModel}_tmp.nc masks_${CplModel}.nc

rm grids_${CplModel}_tmp.nc areas_${CplModel}_tmp.nc masks_${CplModel}_tmp.nc

echo ${Titre}"Generates grid o${oce}, 'o' meaning 'one'"${Norm}
# same as t${oce} grid, with surfaces set to 1
# and mask to 0 (ocean everywhere, to compute integral over the whole grid))
# This grid is used when field are quantities instead of fluxes (i.e river flow)
# --------------------------------------------------------------------------------------------------------
mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
ncap2 --history --script "nav_lon_grid_O=nav_lon_grid_T; nav_lat_grid_O=nav_lat_grid_T; bounds_lon_grid_O=bounds_lon_grid_T; bounds_lat_grid_O=bounds_o${oce}_lat=bounds_lat_grid_T; " grids_${CplModel}_tmp.nc grids_${CplModel}.nc

mv areas_${CplModel}.nc areas_${CplModel}_tmp.nc
ncap2 --history --script "area_grid_O=area_grid_T*0.0d+1.0d;"   areas_${CplModel}_tmp.nc areas_${CplModel}.nc

ncks -C --history --overwrite -v maskutil_T ${OCE}_coordinates_mask.nc maskutil_T.nc
ncap2 --history --append --script "mask_O=maskutil_T; " maskutil_T.nc masks_${CplModel}.nc

rm grids_${CplModel}_tmp.nc areas_${CplModel}_tmp.nc 


echo ${Titre}"Creates OCEAN C grid : redundant points removed to compute proper integrals"${Norm}
# --------------------------------------------------------------------------------------------------------

mv grids_${CplModel}.nc grids_${CplModel}_tmp.nc
ncap2 --history --script "nav_lon_grid_C=nav_lon_grid_T; nav_lat_grid_C=nav_lat_grid_T; bounds_lon_grid_C=bounds_lon_grid_T; bounds_lat_grid_C=bounds_o${oce}_lat=bounds_lat_grid_T; " grids_${CplModel}_tmp.nc grids_${CplModel}.nc

mv areas_${CplModel}.nc areas_${CplModel}_tmp.nc
ncap2 --history --script "area_grid_C=area_grid_T ; "   areas_${CplModel}_tmp.nc areas_${CplModel}.nc

ncap2 --history --append --script "mask_C=maskutil_T; " maskutil_T.nc masks_${CplModel}.nc

rm grids_${CplModel}_tmp.nc areas_${CplModel}_tmp.nc maskutil_T.nc

#
echo ${Titre}"Final renaming"${Norm}
# ----------------------------------------------------------------------------
for OCEGRID in T U V O C
do
    ocegrid=${OCEGRID~} # To lowercase
    ncrename --history --variable nav_lon_grid_${OCEGRID},${ocegrid}${oce}.lon     grids_${CplModel}.nc
    ncrename --history --variable nav_lat_grid_${OCEGRID},${ocegrid}${oce}.lat     grids_${CplModel}.nc
    ncrename --history --variable bounds_lon_grid_${OCEGRID},${ocegrid}${oce}.clo  grids_${CplModel}.nc
    ncrename --history --variable bounds_lat_grid_${OCEGRID},${ocegrid}${oce}.cla  grids_${CplModel}.nc
    ncrename --history --variable mask_${OCEGRID},${ocegrid}${oce}.msk             masks_${CplModel}.nc
    ncrename --history --variable area_grid_${OCEGRID},${ocegrid}${oce}.srf        areas_${CplModel}.nc
    
    ncatted --history \
	    --attribute bounds,${ocegrid}${oce}.lon,m,c,"${ocegrid}${oce}.clo"  \
	    --attribute bounds,${ocegrid}${oce}.lat,m,c,"${ocegrid}${oce}.cla"  \
	    --attribute units,${ocegrid}${oce}.clo,o,c,"degrees_east"        \
	    --attribute units,${ocegrid}${oce}.clo,o,c,"degrees_north" grids_${CplModel}.nc
done

ncrename --history --variable alon,t${atm}.lon                grids_${CplModel}.nc
ncrename --history --variable alat,t${atm}.lat                grids_${CplModel}.nc
ncrename --history --variable Oce2AtmMask,t${atm}.msk         masks_${CplModel}.nc
ncrename --history --variable aire,t${atm}.srf                areas_${CplModel}.nc
ncrename --history --variable bounds_lon,t${atm}.clo          grids_${CplModel}.nc
ncrename --history --variable bounds_lat,t${atm}.cla          grids_${CplModel}.nc

for ATMGRID in O C ; do
    atmgrid=${ATMGRID~} # To lowercase
    ncrename --history --variable ${atmgrid}${atm}_lon,${atmgrid}${atm}.lon         grids_${CplModel}.nc
    ncrename --history --variable ${atmgrid}${atm}_lat,${atmgrid}${atm}.lat         grids_${CplModel}.nc
    ncrename --history --variable ${atmgrid}${atm}_mask,${atmgrid}${atm}.msk        masks_${CplModel}.nc
    ncrename --history --variable ${atmgrid}${atm}_aire,${atmgrid}${atm}.srf        areas_${CplModel}.nc
    ncrename --history --variable bounds_${atmgrid}${atm}_lon,${atmgrid}${atm}.clo  grids_${CplModel}.nc
    ncrename --history --variable bounds_${atmgrid}${atm}_lat,${atmgrid}${atm}.cla  grids_${CplModel}.nc
done
    
for ATMGRID in T O C ; do
    atmgrid=${ATMGRID~} # To lowercase
    ncatted --history \
	    --attribute bounds,${atmgrid}${atm}.lon,c,c,"${atmgrid}${atm}.clo"   \
	    --attribute bounds,${atmgrid}${atm}.lat,c,c,"${atmgrid}${atm}.cla"   \
	    --attribute units,${atmgrid}${atm}.clo,o,c,"degrees_east"            \
	    --attribute units,${atmgrid}${atm}.cla,o,c,"degrees_north"        grids_${CplModel}.nc
done


echo ${Titre}"Add time axis and coordinates information"${Norm}
# (needed if files need to be read by XIOS) ???
## ===========================================================================
ncap2 --overwrite --history --script 'defdim("time_counter",1) ;' ${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}_time.nc

if [[ ${atm} = ico ]] ; then
    cat <<EOF > add_time.nco
OceFrac     [time_counter,cell] = OceFrac     [cell] ;
OceMask     [time_counter,cell] = OceMask     [cell] ;
Oce2AtmMask [time_counter,cell] = Oce2AtmMask [cell] ;
EOF
    ncap2 --overwrite --history --script-file add_time.nco ${ATM}_grid_maskFrom_${OCE}_time.nc tmp_${ATM}_grid_maskFrom_${OCE}_time.nc ; mv tmp_${ATM}_grid_maskFrom_${OCE}_time.nc ${ATM}_grid_maskFrom_${OCE}_time.nc
    ncatted --history \
	    -a coordinates,OceFrac,m,c,"time_counter lat lon"    \
            -a coordinates,OceMask,m,c,"time_counter lat lon"    \
	    -a coordinates,aire,c,c,"lat lon" \
            ${ATM}_grid_maskFrom_${OCE}.nc
fi

if [[ ${atm} = lmd ]] ; then
    cat <<EOF > add_time.nco
OceFrac     [time_counter,y,x] = OceFrac     [y,x] ;
OceMask     [time_counter,y,x] = OceMask     [y,x]  ;
Oce2AtmMask [time_counter,y,x] = Oce2AtmMask [y,x]  ;
EOF
    ncap2 --overwrite --history --script-file add_time.nco ${ATM}_grid_maskFrom_${OCE}_time.nc tmp_${ATM}_grid_maskFrom_${OCE}_time.nc
    ncdump -h tmp_${ATM}_grid_maskFrom_${OCE}_time.nc
    mv tmp_${ATM}_grid_maskFrom_${OCE}_time.nc ${ATM}_grid_maskFrom_${OCE}_time.nc
    
    ncatted --history \
	    -a coordinates,OceFrac,m,c,"time_counter lat lon"    \
            -a coordinates,OceMask,m,c,"time_counter lat lon"    \
            -a coordinates,Oce2AtmMask,m,c,"time_counter lat lon"    \
            -a coordinates,aire,m,c,"lat lon" \
            ${ATM}_grid_maskFrom_${OCE}.nc
fi
ncks --alphabetize --history --overwrite --mk_rec time_counter ${ATM}_grid_maskFrom_${OCE}_time.nc tmp_${ATM}_grid_maskFrom_${OCE}_time.nc
mv tmp_${ATM}_grid_maskFrom_${OCE}_time.nc ${ATM}_grid_maskFrom_${OCE}_time.nc
##
echo ${Titre}"Add some useful information in NetCDF headers"${Norm}
## ===========================================================================
NCO=$(ncks --version |& tail -1|sed 's/ncks //')
for type in areas masks grids ; do
    ncatted --history \
	    --attribute nco_openmp_thread_number,global,d,,            \
	    --attribute LongName,global,d,,                            \
	    --attribute NCO,global,o,c,"NCO netCDF Operator ${NCO} http://nco.sourceforge.net" \
	    --attribute Conventions,global,o,c,"CF-1.6"                \
	    --attribute source,global,o,c,"IPSL Earth system model"    \
	    --attribute group,global,o,c,"ICMC IPSL Climate Modelling Center" \
	    --attribute production,global,o,c,"$(finger ${LOGNAME} | head -1 | awk '{print $4, $5}') " \
	    --attribute Institution,global,o,c,"IPSL https://www.ipsl.fr" \
	    --attribute Ocean,global,o,c,"${OCE} https://www.nemo-ocean.eu"  \
	    --attribute Atmosphere,global,o,c,"${ATM} http://lmdz.lmd.jussieu.fr" \
	    --attribute HOSTNAME,global,o,c,"$(hostname)"              \
	    --attribute LOGNAME,global,o,c,"$(whoami)"                 \
	    --attribute Program,global,o,c,"Generated by ${0}"         \
	    --attribute name,global,o,c,"${type}_${CplModel}.nc"       \
	    --attribute directory,global,o,c,"$(pwd)"                  \
	    --attribute description,global,o,c,"Fields needed by OASIS-MCT" \
	    --attribute title,global,o,c,"${type}_${CplModel}.nc"      \
	    --attribute timeStamp,global,o,c,"$(date)"                 \
	    --attribute associatedFiles,global,o,c,"grids_${CplModel}.nc areas_${CplModel}.nc masks_${CplModel}.nc" \
	    --attribute originalFiles,global,o,c,"${OCE}_coordinates_mask.nc ${ATM}_grid_mask.nc"\
	    --attribute OS,global,o,c,"$(uname -o)"                    \
	    --attribute release,global,o,c,"$(uname -r)"               \
	    --attribute hardware,global,o,c,"$(uname -i)"              \
	    --attribute	SVN_Author,global,o,c,"$Author$"      \
            --attribute SVN_Date,global,o,c,"$Date$" \
	    --attribute SVN_Revision,global,o,c,"$Revision$"                    \
	    --attribute SVN_Id,global,o,c,"$Id$" \
	    --attribute SVN_HeardURL,global,o,c,"$HeadURL $" \
	    ${type}_${CplModel}.nc
done


exit
#
echo ${Titre}"Name of the dimensions ?"${Norm} 
# ----------------------------------------------------------------------------
for OCEGRID in T U V ; do
    ocegrid=${OCEGRID~} # Downcase name of grids
    ncrename --history --dimension  x_grid_${OCEGRID},x${ocegrid}${oce}         grids_${CplModel}.nc
    ncrename --history --dimension  y_grid_${OCEGRID},y${ocegrid}${oce}         grids_${CplModel}.nc
    ncrename --history --dimension  nvertex_grid_${OCEGRID},crn${ocegrid}${oce} grids_${CplModel}.nc
done

## ===========================================================================
echo ${Titre}"Exit from CreateOasisGrids "${Norm}

## ===========================================================================
##
echo ${Titre}"                  That's all folk's !!!   "${Norm}
##
## ===========================================================================
