#!/bin/bash
#MSUB -r WeightsMask        # Job name
#MSUB -o Out_WeightsMask    # Standard output
#MSUB -e Out_WeightsMask    # Error output
#MSUB -eo
#MSUB -n 16                 # Number of processors
#MSUB -T 1800               # Time limit (seconds)
#MSUB -q skylake
#MSUB -Q test
#MSUB -p gen2212
#MSUB -m work

### ===========================================================================
###
### Creates interpolation weights between ORCA and atmosphere grids.
### Interpolates ORCA mask to atmosphere grid.
### Weight files are at OASIS-MCT format.
###
### Atmosphere grid may be lon/lat LMDZ or DYNAMICO icosahedron
###
### Documentation : https://forge.ipsl.jussieu.fr/igcmg/wiki/IPSLCM6/MOSAIX
### ===========================================================================
##
##  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.
##
## SVN information
#  $Author$
#  $Date$
#  $Revision$
#  $Id$
#  $HeadURL$
#
set +vx
export Bold=$(tput bold)  
export Unde=$(tput smul) ; export OffUnde=$(tput rmul)
export Stou=$(tput smso) ; export OffStou=$(tput rmso)
export Reve=$(tput rev ) 
couleurs=( "Black" "Blue" "Green" "Cyan" "Red" "Magenta" "Yellow" "White" )
for i in $(seq 0 7 ) ; do eval "export ${couleurs[$i]}=$(tput setf $i)" ; done
export Norm=$(tput sgr0 )
export Titre=${Bold}${Blue}

##
## Configuration
## ===========================================================================
set -e

#
echo ${Titre}"Defines models"${Norm}
# ==============
OCE=ORCA2.3
#OCE=eORCA1.2
#OCE=eORCA025

#ATM=ICO30
#ATM=ICO40
#ATM=ICO450
ATM=LMD9695
#ATM=LMD144142
#ATM=LMD256256

# Runoff parameter (LMDZ grids only)
atmCoastWidth=2 ; oceCoastWidth=2 ; searchRadius=1000.0

if [[ ${OCE} = ORCA2.3  && ${ATM} = LMD9695   ]] ; then atmCoastWidth=2 ; oceCoastWidth=1 ; searchRadius=1000.0 ; fi
if [[ ${OCE} = ORCA2.3  && ${ATM} = LMD144142 ]] ; then atmCoastWidth=2 ; oceCoastWidth=1 ; searchRadius=1000.0 ; fi
if [[ ${OCE} = eORCA1.2 && ${ATM} = LMD9695   ]] ; then atmCoastWidth=2 ; oceCoastWidth=3 ; searchRadius=1000.0 ; fi
if [[ ${OCE} = eORCA1.2 && ${ATM} = LMD144142 ]] ; then atmCoastWidth=2 ; oceCoastWidth=3 ; searchRadius=1000.0 ; fi

# Default values, used to create ocean fraction on atmospheric grid 
DefaultValues=( Direction=o2a,oceGrid=t,atmGrid=t,Order=1st,Quantity=false,Renormalize=false,useArea=false,maskSrc=true,maskDst=false )

## List of weights to build
## ====================================================================================================================================
#
# Each item in CommandList describes the properties of interpolation weights to generate. 
# White spaces separate analysis. No spaces in any analysis.
#
# Specific commands : 'Runoff', 'Calving'
#
# Keywords : 
#   Direction   : o2a for ocean to atmosphere, a2o for atmosphere to ocean
#   Order       : 1st or 2nd
#   Quantity    : true if integrated quantity over a grid box, false for flux (quantity / m^2)
#                 or intensive value (temperature, salinity, sea-ice fraction, ...)
#   Renormalize : used when source grid is masked, to use values on non masked points only
#   oceGrid     : t, u or v point for NEMO C grid
#   atmGrid     : up to know, only t grid used in the atmosphere
#   useArea     : if true area from the model metrics is used. If false, areas are computed by XIOS from grid corners
#   maskSrc     : true to use the source grid mask, false to used all grid points
#   maskDst     : true to use the destination grid mask, false to use all grid points
#
# Classic cases 
AtmOceFluxes=" Direction=a2o,Order=1st,Quantity=false,Renormalize=false,atmGrid=t,oceGrid=t,useArea=true,maskSrc=true,maskDst=true" # Heat and water fluxes
OceAtmTemp="   Direction=o2a,Order=1st,Quantity=false,Renormalize=true,oceGrid=t,atmGrid=t,useArea=false,maskSrc=true,maskDst=true" # Temperature, sea-ice fraction, albedo
AtmOceStressU="Direction=a2o,Order=2nd,Quantity=false,Renormalize=false,atmGrid=t,oceGrid=u,useArea=true,maskSrc=true,maskDst=true" # Wind stress to NEMO U point
AtmOceStressV="Direction=a2o,Order=2nd,Quantity=false,Renormalize=false,atmGrid=t,oceGrid=v,useArea=true,maskSrc=true,maskDst=true" # Wind stress to NEMO V point
# Other cases
OceAtmFluxes=" Direction=o2a,Order=1st,Quantity=false,Renormalize=false,atmGrid=t,oceGrid=t,useArea=true,maskSrc=true,maskDst=true" # e.g. CO2 fluxes
AtmOceTemp="   Direction=o2a,Order=1st,Quantity=false,Renormalize=true,oceGrid=t,atmGrid=t,useArea=false,maskSrc=true,maskDst=true" # e.g. T and S correction from DWL parametrization
AtmOceCoastal="Direction=a2o,Order=1st,Quantity=true,Renormalize=false,atmGrid=c,oceGrid=t,useArea=true,maskSrc=true,maskDst=true"  # Runoff atm to oce, limited to oce coastal points

CommandList=( ${AtmOceFluxes} Runoff Calving )

#CommandList=( Runoff Calving ) #\
#    Direction=o2a,Order=1st,Quantity=false,Renormalize=true,oceGrid=t,atmGrid=t,useArea=false,maskSrc=true,maskDst=true  \
#    Direction=a2o,Order=1st,Quantity=false,Renormalize=false,atmGrid=t,oceGrid=t,useArea=true,maskSrc=true,maskDst=true  \
#    Direction=a2o,Order=2nd,Quantity=false,Renormalize=false,atmGrid=t,oceGrid=u,useArea=true,maskSrc=true,maskDst=true  \
#    Direction=a2o,Order=2nd,Quantity=false,Renormalize=false,atmGrid=t,oceGrid=v,useArea=true,maskSrc=true,maskDst=true  \
#    Direction=a2o,Order=1st,Quantity=true,Renormalize=false,atmGrid=c,oceGrid=t,useArea=true,maskSrc=true,maskDst=true   \
#    Calving \
#    Runoff  \
#    )



Comment="Preliminary attempt - Do not trust !"
#Version

## ===========================================================================
##
## You should not change anything below this line ....
##
## ===========================================================================
SUBMIT_DIR=$(pwd)

# Functions to handle command parameters
# ======================================
function read_Command {
    # Decipher the command line to set bash variables 
    local l_Debug="no" l_Element
    while [[ ${1} = -* ]] ; do
	case ${1} in
	    ( -- ) shift ; break ;;
	    ( -d | --debug ) l_Debug="true" ; shift ;;
	esac
    done
    local l_Command=${1}
    for l_Element in $(echo ${l_Command} | tr "," "\n" ) ; do
	[[ "X${l_Debug}" = "Xtrue" ]] && echo ${l_Element}
	eval export ${l_Element}
    done
}

function setValues {
    #
    oceGrid=${oceGrid,,} ; atmGrid=${atmGrid,,}
    OCEGRID=${oceGrid^^} ; ATMGRID=${atmGrid^^}

    case ${Order} in
	( 1st ) numOrder=1 ;;
	( 2nd ) numOrder=2 ;;
    esac
    case ${Renormalize} in
	( true )  NormName=Normalized   ;;
	( false ) NormName=UnNormalized ;;
    esac
    case ${Quantity} in
	( true )  QuantName=Integrated ;;
	( false ) QuantName=Surfacic   ;;
    esac
    case ${useArea} in
	( true )  AreaName=Area   ;;
	( false ) AreaName=NoArea ;;
    esac
    
    Suffix=${Order}Order_${NormName}_${QuantName}_${AreaName}

    case ${Direction} in
	( o2a )
	src=${oce} ; SRC=${OCE} ; srcGrid=${oceGrid} ; srcDomainType=${oceDomainType} ; SRCGRID=${OCEGRID} ; srcArea=area_grid_${OCEGRID}
	dst=${atm} ; DST=${ATM} ; dstGrid=${atmGrid} ; dstDomainType=${atmDomainType} ; DSTGRID=${ATMGRID} ; dstArea=aire
	;; 
	( a2o )
	src=${atm} ; SRC=${ATM} ; srcGrid=${atmGrid} ; srcDomainType=${atmDomainType} ; SRCGRID=${ATMGRID} ; srcArea=aire
	dst=${oce} ; DST=${OCE} ; dstGrid=${oceGrid} ; dstDomainType=${oceDomainType} ; DSTGRID=${OCEGRID} ; dstArea=area_grid_${OCEGRID}
	;;
    esac
    echo ${Green}"${SRC} ${SRCGRID} toward ${DST} ${DSTGRID} - ${Order} Order - Normalize: ${Renormalize} - Quantity: ${QuantName} - Area: ${AreaName}  "${Norm}	     
}
    
#
# Defines computer
# ================
if [[ $(hostname) = irene*    ]] ; then arch=irene ; center=tgcc ; fi
if [[ $(hostname) = lsce*     ]] ; then arch=spip  ; center=spip ; fi

PROGRAM=$(basename ${0})

case ${arch} in
    ( irene )
    set +vx
    R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
    TMPDIR=${CCCWORKDIR}/TMP
    SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
    PROGRAM=${BRIDGE_MSUB_REQNAME}
    MpiRun="time ccc_mprun"
    PyRun="ccc_mprun -n 1"
    source ${SUBMIT_DIR}/arch.env
    module load nco
    #source $(ccc_home -u igcmg)/MachineEnvironment/irene/env_irene
    module load python3 
    module load datadir/igcmg
    module list
    ;;
    ( 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

set -x ; set -e

mkdir -p ${TMPDIR}/${OCE}x${ATM} || exit 1
cd       ${TMPDIR}/${OCE}x${ATM} || exit 1
rm -fr *

#
# Suffixes
# ---------------------------------------------------------------------------

case ${OCE} in
    ( *ORC* )         oce=orc ; oceDomainType=curvilinear   ;;
esac

case ${ATM} in
    ( *dynamico*    ) atm=ico ; atmDomainType=unstructured  ;;
    ( *ICO*         ) atm=ico ; atmDomainType=unstructured  ;;
    ( *lmd* | *LMD* ) atm=lmd ; atmDomainType=rectilinear   ;;
esac

case ${OCE} in # Periodicity type of ORCA grid
    ( ORCA2.3*             ) OcePerio=4 ;;
    ( ORCA1*   | eORCA1*   ) OcePerio=6 ;;
    ( ORCA025* | eORCA025  ) OcePerio=6 ;;
esac
#
echo ${Titre}"Format for OASIS files : should be NetCDF3 classic or NetCDF3 64 bits"${Norm}
# ---------------------------------------------------------------------------
FMT_OASIS=64bit
FMT_XIOS=netcdf4

cp ${SUBMIT_DIR}/bin/interpol.exe    .
cp ${SUBMIT_DIR}/*.py                .
cp ${SUBMIT_DIR}/iodef_atm_to_oce.xml   .
cp ${SUBMIT_DIR}/iodef_oce_to_atm.xml   .

cp ${R_IN}/OCE/NEMO/${OCE}/${OCE}_coordinates_mask.nc  .
cp ${R_IN}/ATM/GRID/${ATM}_grid.nc .

ncks --overwrite --fl_fmt=${FMT_OASIS} --history ${OCE}_coordinates_mask.nc ${OCE}_coordinates_mask_${FMT_OASIS}.nc
ncks --overwrite --fl_fmt=${FMT_OASIS} --history ${ATM}_grid.nc             ${ATM}_grid_${FMT_OASIS}.nc
#
echo ${Titre}"Creates OCEAN C grid : redundant points removed to compute proper integrals # A passer dans CreateWeights"${Norm}
# --------------------------------------------------------------------------------------------------------
cat <<EOF >add_c_grid.nco
defdim("x_grid_C", \$x_grid_T.size) ;
defdim("y_grid_C", \$y_grid_T.size) ;
defdim("nvertex_grid_C",  4)         ;
nav_lon_grid_C[y_grid_C,x_grid_C]    = nav_lon_grid_T(:,:)    ;
nav_lat_grid_C[y_grid_C,x_grid_C]    = nav_lat_grid_T(:,:)    ;
bounds_lon_grid_C[y_grid_C,x_grid_C,nvertex_grid_C] = bounds_lon_grid_T(:,:,:) ;
bounds_lat_grid_C[y_grid_C,x_grid_C,nvertex_grid_C] = bounds_lat_grid_T(:,:,:) ;
mask_C[y_grid_C,x_grid_C]            = maskutil_T(:,:)        ; 
area_grid_C[y_grid_C,x_grid_C]       = area_grid_T(:,:)       ;
EOF

ncap2 --overwrite --history --script-file add_c_grid.nco ${OCE}_coordinates_mask.nc tmp_${OCE}_coordinates_mask.nc
ncatted --history --attribute bounds,nav_lon_grid_C,m,c,"bounds_lon_grid_C" tmp_${OCE}_coordinates_mask.nc
ncatted --history --attribute bounds,nav_lat_grid_C,m,c,"bounds_lat_grid_C" tmp_${OCE}_coordinates_mask.nc
ncks --history --overwrite --variable nav_lon_grid_C,nav_lat_grid_C       tmp_${OCE}_coordinates_mask.nc C_${OCE}_coordinates_mask.nc
ncks --history --append    --variable bounds_lon_grid_C,bounds_lat_grid_C tmp_${OCE}_coordinates_mask.nc C_${OCE}_coordinates_mask.nc
ncks --history --append    --variable area_grid_C             tmp_${OCE}_coordinates_mask.nc C_${OCE}_coordinates_mask.nc 

ncks --history --append C_${OCE}_coordinates_mask.nc            ${OCE}_coordinates_mask.nc
rm C_${OCE}_coordinates_mask.nc

ncks --history --overwrite --fl_fmt=${FMT_OASIS} ${OCE}_coordinates_mask.nc ${OCE}_coordinates_mask_${FMT_OASIS}.nc

ls -al

##
echo ${Titre}"NEMO T point towards ATM - 1st order"${Norm}
## ===========================================================================
echo "Command parameters : ${Command}"
read_Command ${DefaultValues}
read_Command ${Command}
setValues

cp iodef_oce_to_atm.xml   iodef.xml

python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_src"]/field[@id="mask_src"]'   -k name  -v maskutil_T
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_src"]/field[@id="area_src"]'   -k name  -v area_grid_T
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_src"]'                   -k type  -v ${srcDomainType}
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_dst"]'                   -k type  -v ${dstDomainType}
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k order -v 1
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k quantity    -v false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k renormalize -v false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k use_area -v false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="mask_source"]' -k name  -v maskutil_T
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="area_source"]' -k name  -v area_grid_T
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]'                               -k name  -v dia_${srcGrid}${src}_to_${dstGrid}${dst}_${Suffix}
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="title"]'       -t "${SRC} mask interpolated to ${DST}"
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="source_grid"]' -t ${srcDomainType}
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t ${dstDomainType}
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="order"]'       -t 1
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_src"]'                    -k type  -v ${srcDomainType}
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]'                    -k type  -v ${dstDomainType}
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k weight_filename -v rmp_${srcGrid}${src}_to_${dstGrid}${dst}_${Suffix}.nc
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k order -v 1
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="normalization"]' -t false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="quantity"]'      -t false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="use_area"]'      -t false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k renormalize -v false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k quantity    -v false
python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k use_area    -v false

cp iodef.xml iodef_${srcGrid}${src}_to_${dstGrid}${dst}_${Suffix}.xml
ln -fs ${OCE}_coordinates_mask.nc  oce_grid.nc
ln -fs ${ATM}_grid.nc              atm_grid.nc

${MpiRun} ./interpol.exe --mask_src=${maskSrc} --mask_dst=${maskDst} --use_area=${useArea}

##
echo ${Titre}"Correct spurious values (extremes)"${Norm}
## ===========================================================================
cat <<EOF > correction_masque.nco
where (OceFrac <   0.00001 )  OceFrac=OceFrac.get_miss() ;
where (OceFrac >   0.99999 )  OceFrac=1.0 ;
OceFrac.delete_miss() ;
// Fill masked values to land values
where (OceFrac >  1.0 )  OceFrac=0.0 ;
where (OceFrac <  0.0 )  OceFrac=0.0 ; 
EOF
ncap2 --history --overwrite --script-file correction_masque.nco dia_t${oce}_to_t${atm}_${Suffix}.nc tmp_dia_t${oce}_to_t${atm}_${Suffix}.nc ; mv tmp_dia_t${oce}_to_t${atm}_${Suffix}.nc dia_t${oce}_to_t${atm}_${Suffix}.nc
ncatted --history -a missing_value,OceFrac,d,,"" -a _FillValue,OceFrac,d,,"" dia_t${oce}_to_t${atm}_${Suffix}.nc

##
echo ${Titre}"Creates ocean fractions on ATM grid"${Norm}
## ===========================================================================
cp dia_t${oce}_to_t${atm}_${Suffix}.nc  dia_t${oce}_to_t${atm}_${Suffix}_mask.nc
ncks --alphabetize --history --overwrite --variable OceFrac dia_t${oce}_to_t${atm}_${Suffix}_mask.nc  ${ATM}_grid_maskFrom_${OCE}.nc

cat <<EOF > creation_masque.nco
where (OceFrac >  0.0 )  OceFrac=1 ;
where (OceFrac <= 0.0 )  OceFrac=0 ;
EOF

ncap2 --history --overwrite --script-file creation_masque.nco dia_t${oce}_to_t${atm}_${Suffix}_mask.nc tmp_dia_t${oce}_to_t${atm}_${Suffix}_mask.nc ; mv tmp_dia_t${oce}_to_t${atm}_${Suffix}_mask.nc dia_t${oce}_to_t${atm}_${Suffix}_mask.nc
ncrename --history --variable OceFrac,OceMask dia_t${oce}_to_t${atm}_${Suffix}_mask.nc

ncks --overwrite --history --variable OceMask dia_t${oce}_to_t${atm}_${Suffix}_mask.nc tmp_OceMask.nc
ncks --history --append tmp_OceMask.nc ${ATM}_grid_maskFrom_${OCE}.nc
rm dia_t${oce}_to_t${atm}_${Suffix}_mask.nc

echo "Change dimension names, and some attributes accordingly"
if [[ $(ncdump -h ${ATM}_grid_maskFrom_${OCE}.nc | grep domain_dst | wc -l) -gt 0 ]] ; then
    case ${atm} in
	( *ico* ) 
	ncrename --history --dimension cell_domain_dst,cell              ${ATM}_grid_maskFrom_${OCE}.nc
	ncrename --history --dimension nvertex_domain_dst,nvertex        ${ATM}_grid_maskFrom_${OCE}.nc
	ncrename --history --variable  lat_domain_dst,lat                ${ATM}_grid_maskFrom_${OCE}.nc
	ncrename --history --variable  lon_domain_dst,lon                ${ATM}_grid_maskFrom_${OCE}.nc
	ncrename --history --variable  bounds_lat_domain_dst,bounds_lat  ${ATM}_grid_maskFrom_${OCE}.nc
	ncrename --history --variable  bounds_lon_domain_dst,bounds_lon  ${ATM}_grid_maskFrom_${OCE}.nc
	ncatted  --history --attribute bounds,lat,m,c,"bounds_lat"       ${ATM}_grid_maskFrom_${OCE}.nc
	ncatted  --history --attribute bounds,lon,m,c,"bounds_lon"       ${ATM}_grid_maskFrom_${OCE}.nc
	;;
	( *lmd* ) 
	ncrename --history --dimension lon_domain_dst,lon            ${ATM}_grid_maskFrom_${OCE}.nc
	ncrename --history --dimension lat_domain_dst,lat            ${ATM}_grid_maskFrom_${OCE}.nc
	;;
    esac
    ncatted  --history --attribute coordinates,OceFrac,m,c,"lat lon" ${ATM}_grid_maskFrom_${OCE}.nc
    ncatted  --history --attribute coordinates,OceMask,m,c,"lat lon" ${ATM}_grid_maskFrom_${OCE}.nc
 
fi

ncks --history --alphabetize  --append    --variable aire    atm_grid.nc                                   ${ATM}_grid_maskFrom_${OCE}.nc
[[ ${atm} = *ico* ]] && ncks --alphabetize --history --append --variable bounds_lon,bounds_lat atm_grid.nc ${ATM}_grid_maskFrom_${OCE}.nc

##
echo ${Titre}"Creates mask of coastal OCE points"${Norm}
## ===========================================================================
${PyRun} python3 -u ComputeNemoCoast.py -n ${OcePerio} -i ${OCE}_coordinates_mask.nc # Creates OceCoastal

##
echo ${Titre}"Creates mask of coastal ATM points"${Norm}
## ===========================================================================
cat <<EOF > coastal.nco
AtmCoastal = OceFrac * 0.0 ;
where (OceFrac > 0.0 && OceFrac < 1.0 )  AtmCoastal = 1.0 ;
EOF
ncap2 --history --overwrite --script-file coastal.nco ${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_coastal_maskFrom_${OCE}.nc
ncks --history --append --variable AtmCoastal ${ATM}_coastal_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc
rm ${ATM}_coastal_maskFrom_${OCE}.nc
ncks --alphabetize --history --overwrite --fl_fmt=${FMT_OASIS} ${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc


##
echo ${Titre}"Other weights files"${Norm}
## ===========================================================================
# Loop on commands
for Command in ${CommandList[@]}
do
    echo "Command parameters : ${Command}"
    read_Command ${DefaultValues}
    read_Command ${Command}

    if [[ ${Command} = "Runoff"  ]] ; then okRunoff=yes  ; continue ; fi
    if [[ ${Command} = "Calving" ]] ; then okCalving=yes ; continue ; fi
    
    setValues
    
    ln -fs ${OCE}_coordinates_mask.nc  oce_grid.nc
    ln -fs ${ATM}_grid.nc              atm_grid.nc
    
    case ${Direction} in
	( o2a )
	cp iodef_oce_to_atm.xml iodef.xml
	
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_src"]/field[@id="mask_src"]'   -k name -v mask_${DSTGRID} 
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_dst"]/field[@id="mask_dst"]'   -k name -v OceMask
	
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="mask_source"]' -k name -v maskutil_${SRCGRID}
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="area_source"]' -k name -v area_grid_${SRCGRID}
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_dst"]/field[@id="mask_dest"]'   -k name -v OceMask
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_dst"]/field[@id="area_dest"]'   -k name -v aire
	;;
	( a2o )
	cp iodef_atm_to_oce.xml iodef.xml
	
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_src"]/field[@id="mask_src"]'   -k name -v OceMask
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_dst"]/field[@id="mask_dst"]'   -k name -v mask_${DSTGRID}
	
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="mask_source"]' -k name  -v OceMask
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="area_source"]' -k name  -v aire
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_dst"]/field[@id="mask_dest"]'   -k name  -v mask_${DSTGRID}
	python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_dst"]/field[@id="area_dest"]'   -k name  -v area_grid_${DSTGRID}
	;;
    esac
    
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_dst"]'                     -k type  -v ${dstDomainType}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_src"]'                     -k type  -v ${srcDomainType}
    
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_src"]'                      -k type  -v ${srcDomainType}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]'                      -k type  -v ${dstDomainType}
    
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k weight_filename -v rmp_${srcGrid}${src}_to_${dstGrid}${dst}_${Suffix}.nc
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k order       -v ${numOrder}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k quantity    -v ${Quantity}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k renormalize -v ${Renormalize}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k use_area    -v ${useArea}
    
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]'                                 -k name -v dia_${srcGrid}${src}_to_${dstGrid}${dst}_${Suffix}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="title"]'         -t "${SRC} mask interpolated to ${DST}"
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'     -t ${dstDomainType}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="source_grid"]'   -t ${srcDomainType}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="normalization"]' -t ${Renormalize}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="order"]'         -t ${numOrder}   
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="quantity"]'      -t ${Quantity}
    python3 update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="use_area"]'      -t ${useArea}
    
    cp iodef.xml iodef_${srcGrid}${src}_to_${dstGrid}${dst}_${Suffix}.xml
    ${MpiRun} ./interpol.exe --mask_src=${maskSrc} --mask_dst=${maskDst} --use_area=${useArea}
done

##
echo ${Titre}"Copy all NetCDF files to NetCDF 3 format (needed for OASIS)"${Norm}
## ===========================================================================
for InFile in *.nc ; do
    OuFile=$(basename ${InFile} .nc)_${FMT_OASIS}.nc
    [[ ! -f ${OuFile} ]] && ncks --alphabetize --history --fl_fmt=${FMT_OASIS} ${InFile} ${OuFile}
done

##
echo ${Titre}"Add time axis and coordinates information"${Norm}
## (needed if files need to be read by XIOS)
## ===========================================================================
#ncatted --history -a coordinates,aire,m,c,"lat lon" ${ATM}_grid_maskFrom_${OCE}.nc
ncap2 --overwrite --history --script 'defdim("time_counter",1) ;' ${ATM}_grid_maskFrom_${OCE}.nc tmp_${ATM}_grid_maskFrom_${OCE}.nc ; mv tmp_${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc

ncks --alphabetize --history --overwrite --fl_fmt=${FMT_OASIS} ${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc

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

if [[ ${atm} = lmd ]] ; then
    cat <<EOF > add_time.nco
OceFrac    [time_counter,lat,lon] = OceFrac    [lat,lon] ;
OceMask    [time_counter,lat,lon] = OceMask    [lat,lon]  ;
AtmCoastal [time_counter,lat,lon] = AtmCoastal [lat,lon]  ;
EOF
    ncap2 --overwrite --history --script-file add_time.nco ${ATM}_grid_maskFrom_${OCE}.nc tmp_${ATM}_grid_maskFrom_${OCE}.nc
    ncdump -h tmp_${ATM}_grid_maskFrom_${OCE}.nc
    mv tmp_${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc
    
    ncatted --history \
	    -a coordinates,OceFrac,m,c,"time_counter lat lon"    \
            -a coordinates,OceMask,m,c,"time_counter lat lon"    \
            -a coordinates,AtmCoastal,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}.nc tmp_${ATM}_grid_maskFrom_${OCE}.nc ; mv tmp_${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}.nc
ncks --alphabetize --history --overwrite --fl_fmt=${FMT_OASIS} ${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc

##
echo ${Titre}"Add some metadata in file headers"${Norm}
## ===========================================================================

UUID=$(uuid)
NCO="$(ncks --version |& tail -1|sed 's/ncks //')"
PYTHON_VER=$( python3 -c "import sys ; print (sys.version.split(' ')[0])" )
for InFile in $(ls *${oce}_to_*${atm}_*.nc *${atm}_to_*${oce}_*.nc ${ATM}_grid_maskFrom_${OCE}.nc ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc 2>/dev/null) ; do
    ncatted --history \
	    --attribute uuid,global,d,,                                           \
	    --attribute LongName,global,d,,                                       \
	    --attribute nco_openmp_thread_number,global,d,,                       \
	    --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 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 production,global,o,c,"$(finger ${LOGNAME} | head -1 | awk '{print $4, $5}') " \
	    --attribute originalFiles,global,o,c,"${OCE}_coordinates_mask.nc ${ATM}_grid_mask.nc"      \
	    --attribute associatedFiles,global,o,c,"grids_${OCE}x${ATM}.nc areas_${OCE}x${ATM}.nc masks_${OCE}x${ATM}.nc" \
	    --attribute directory,global,o,c,"$(pwd)"                             \
	    --attribute description,global,o,c,"Fields needed by OASIS-MCT"       \
	    --attribute title,global,o,c,"${InFile}.nc"                           \
	    --attribute Program,global,o,c,"Generated by ${PROGRAM}"              \
	    --attribute timeStamp,global,o,c,"$(date)"                            \
	    --attribute uuid,global,o,c,"${UUID}"                                 \
	    --attribute HOSTNAME,global,o,c,"$(hostname)"                         \
	    --attribute LOGNAME,global,o,c,"$(whoami)"                            \
	    --attribute NCO,global,o,c,"NCO netCDF Operator ${NCO} http://nco.sourceforge.net" \
	    --attribute Python,global,o,c,"Python3 version ${PYTHON_VER}"          \
	    --attribute OS,global,o,c,"$(uname -o)"                               \
	    --attribute release,global,o,c,"$(uname -r)"                          \
	    --attribute directory,global,o,c,"$(pwd)"                             \
	    --attribute description,global,o,c,"Generated with XIOS http://forge.ipsl.jussieu.fr/ioserver and MOSAIX https://forge.ipsl.jussieu.fr/igcmg/browser/TOOLS/MOSAIX" \
	    --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$'                                \
	    ${InFile}
done
##
echo ${Titre}"Update and complete weight files to fit OASIS requested format"${Norm}
## ===========================================================================
cat <<EOF > add_dim.nco
defdim("num_wgts",1) ;
weight[n_weight, num_wgts] = weight ;
EOF

for rmpFile in rmp_*.nc ; do
    mv ${rmpFile} xios_${rmpFile}
    ncap2 --fl_fmt=${FMT_OASIS} --history --script-file add_dim.nco xios_${rmpFile} ${rmpFile}
    
    ncrename --history --dimension n_weight,num_links   ${rmpFile}
    ncrename --history --variable  src_idx,src_address  ${rmpFile}
    ncrename --history --variable  dst_idx,dst_address  ${rmpFile}
    ncrename --history --variable  weight,remap_matrix  ${rmpFile}
    case ${rmpFile} in
	( *1storder* ) ncatted --history --attribute map_method,global,o,c,"Conservative Remapping - 1st order"  ${rmpFile} ;;
	( *2ndorder* ) ncatted --history --attribute map_method,global,o,c,"Conservative Remapping - 2nd order"  ${rmpFile} ;;
    esac
    case ${rmpFile} in
	( *_Normalized*   ) ncatted --history --attribute map_method,global,o,c,"Normalization: true"  ${rmpFile} ;;
	( *_UnNormalized* ) ncatted --history --attribute map_method,global,o,c,"Normalization: false" ${rmpFile} ;;
    esac
    case ${rmpFile} in
	( *Integrated*   ) ncatted --history --attribute map_method,global,o,c,"Quantity: true"  ${rmpFile} ;;
	( *Surfacic*     ) ncatted --history --attribute map_method,global,o,c,"Quantity: false" ${rmpFile} ;;
    esac
    ncatted --history --attribute conventions,global,o,c,"SCRIP"   ${rmpFile}
    ncatted --history --attribute normalization,global,o,c,"none"  ${rmpFile}
    
    case ${rmpFile} in
	( rmp_*${oce}_to_t${atm}_* )
	ncatted --history \
		--attribute title,global,o,c,"Weights ${OCE} to ${ATM}" \
		--attribute source_grid,global,o,c,"${oceDomainType}" \
		--attribute dest_grid,global,o,c,"${atmDomainType}"   \
		${rmpFile}	
	;;
	( rmp_*${atm}_to_*${oce}_* )
	ncatted --history \
		--attribute title,global,o,c,"Weights ${ATM} to ${OCE}" \
		--attribute source_grid,global,o,c,"${atmDomainType}" \
		--attribute dest_grid,global,o,c,"${oceDomainType}"   \
		${rmpFile}
	;;
    esac
done

##
echo ${Titre}"Add missing variables in rmp files"${Norm}
## ===========================================================================
for $(ls rmpFile in rmp_?${atm}_to_[tuv]${oce}_*.nc rmp_[tuv]${oce}_to_t${atm}_*.nc* 2>/dev/null) ; do
    echo ${rmpFile}
    a_to_o=false ; o_to_a=false
    case ${rmpFile} in
	(  rmp_?${oce}_to_?${atm}_*.nc ) o_to_a=true ;;
	(  rmp_?${atm}_to_?${oce}_*.nc ) a_to_o=true ;;
    esac

    for Grid in t u v o c ; do # Identify grids
	[[ ${rmpFile} = rmp_${Grid}${oce}_to_?${atm}_*.nc ]] && ogrid=${Grid}
	[[ ${rmpFile} = rmp_?${oce}_to_${Grid}${atm}_*.nc ]] && agrid=${Grid}
	[[ ${rmpFile} = rmp_${Grid}${atm}_to_?${oce}_*.nc ]] && agrid=${Grid}
	[[ ${rmpFile} = rmp_?${atm}_to_${Grid}${oce}_*.nc ]] && ogrid=${Grid}
    done
    OGRID=${ogrid^}
    AGRID=${agrid^}
	
    cat <<EOF >add_varoce.nco
defdim ("src_grid_size"   , \$x_grid_${OGRID}.size*\$y_grid_${OGRID}.size) ;
defdim ("src_grid_corners", 4) ;
defdim ("src_grid_rank"   , 2) ;
//
src_grid_dims[src_grid_rank] = { \$y_grid_${OGRID}.size, \$x_grid_${OGRID}.size } ;
//
src_grid_center_lat [src_grid_size] =  0.0d ;
src_grid_center_lon [src_grid_size] =  0.0d ;
src_grid_center_lat (:) = nav_lat_grid_${OGRID}(:,:)   ;
src_grid_center_lon (:) = nav_lon_grid_${OGRID}(:,:)   ;
//
src_grid_corner_lat [src_grid_size, src_grid_corners] = 0.0d ;
src_grid_corner_lon [src_grid_size, src_grid_corners] = 0.0d ;
src_grid_corner_lat(:,:) = bounds_lat_grid_${OGRID}(:,:,:) ;
src_grid_corner_lon(:,:) = bounds_lon_grid_${OGRID}(:,:,:) ;
//
src_grid_imask [src_grid_size] =    0 ;
src_grid_area  [src_grid_size] = 0.0d ;
src_grid_frac  [src_grid_size] = 1.0d ;
src_grid_imask (:) = 1 - mask_${OGRID}(:,:) ;
src_grid_imask.int() ;
src_grid_area  (:) = area_grid_${OGRID}(:,:) ;
EOF

    cp add_varoce.nco add_varoce_$(basename ${rmpFile} .nc)_o_to_a.nco
    [[ ${o_to_a} = true ]] && ncap2 --history --append --script-file add_varoce_$(basename ${rmpFile} .nc)_o_to_a.nco ${OCE}_coordinates_mask_${FMT_OASIS}.nc ${rmpFile}
    sed --in-place "s/src_/dst_/g" add_varoce.nco
    cp add_varoce.nco add_varoce_$(basename ${rmpFile} .nc)_a_to_o.nco
    [[ ${a_to_o} = true ]] && ncap2 --history --append --script-file add_varoce_$(basename ${rmpFile} .nc)_a_to_o.nco ${OCE}_coordinates_mask_${FMT_OASIS}.nc ${rmpFile}
		
    if [[ ${atm} = ico ]] ; then
	cat <<EOF >add_varatm.nco
defdim ("dst_grid_size"   , \$cell.size) ;
defdim ("dst_grid_corners", 6) ;
defdim ("dst_grid_rank"   , 2) ;
//
dst_grid_dims[dst_grid_rank] = { \$cell.size, 1 } ;
//
dst_grid_center_lat [dst_grid_size] =  0.0d ;
dst_grid_center_lon [dst_grid_size] =  0.0d ;
dst_grid_center_lat (:) = lat(:)   ;
dst_grid_center_lon (:) = lon(:)   ;
//
dst_grid_corner_lat [dst_grid_size, dst_grid_corners] = 0.0d ;
dst_grid_corner_lon [dst_grid_size, dst_grid_corners] = 0.0d ;
dst_grid_corner_lat(:,:) = bounds_lat(:,:) ;
dst_grid_corner_lon(:,:) = bounds_lon(:,:) ;
//
dst_grid_imask [dst_grid_size] =    0 ;
dst_grid_area  [dst_grid_size] = 0.0d ;
dst_grid_frac  [dst_grid_size] = 1.0d ;
dst_grid_imask (:) = 1 - OceMask(0,:) ;
dst_grid_imask.int() ;
dst_grid_area  (:) = aire(:) ;
dst_grid_frac  (:) = OceFrac(0,:) ;
EOF
	cp add_varatm.nco add_varatm_$(basename ${rmpFile} .nc)_o_to_a.nco
	if [[ ${o_to_a} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm_$(basename ${rmpFile} .nc)_o_to_a.nco ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc ${rmpFile}
	    ncks --alphabetize --history --overwrite --variable src_address,dst_address,remap_matrix,src_grid_dims,src_grid_center_lat,src_grid_center_lon,src_grid_corner_lon,src_grid_corner_lat,src_grid_area,src_grid_imask,dst_grid_dims,dst_grid_center_lat,dst_grid_center_lon,dst_grid_corner_lon,dst_grid_corner_lat,dst_grid_area,dst_grid_imask ${rmpFile} rmp_tmp.nc
	    mv rmp_tmp.nc ${rmpFile}
	fi
		    
	sed --in-place "s/dst_/src_/g" add_varatm.nco
	cp add_varatm.nco add_varatm_$(basename ${rmpFile} .nc)_a_to_o.nco
	if [[ ${a_to_o} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm_$(basename ${rmpFile} .nc)_a_to_o.nco ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc ${rmpFile}
	    ncks --alphabetize --history --overwrite --variable src_address,dst_address,remap_matrix,src_grid_dims,src_grid_center_lat,src_grid_center_lon,src_grid_corner_lon,src_grid_corner_lat,src_grid_area,src_grid_imask,dst_grid_dims,dst_grid_center_lat,dst_grid_center_lon,dst_grid_corner_lon,dst_grid_corner_lat,dst_grid_area,dst_grid_imask ${rmpFile} rmp_tmp.nc
	    mv rmp_tmp.nc ${rmpFile}
	fi
    fi
    
    if [[ ${atm} = lmd ]] ; then
	cat <<EOF >add_varatm.nco
defdim ("dst_grid_size"   , \$lon.size*\$lat.size) ;
defdim ("dst_grid_corners", 4) ;
defdim ("dst_grid_rank"   , 2) ;
//
dst_grid_dims[dst_grid_rank] = { \$lat.size, \$lon.size } ;
//
dst_grid_center_lat [dst_grid_size] =  0.0d ;
dst_grid_center_lon [dst_grid_size] =  0.0d ;
lat0lon[lat,lon] = lat(:)+0*lon(:) ; 
lon0lat[lat,lon] = lon(:)+0*lat(:) ;
dst_grid_center_lat (:) = lat0lon(:,:)   ;
dst_grid_center_lon (:) = lon0lat(:,:)   ;
//
//dst_grid_corner_lat [dst_grid_size, dst_grid_corners] = 0.0d ; // Not available for LMDZ lon/lat grid
//dst_grid_corner_lon [dst_grid_size, dst_grid_corners] = 0.0d ;
//dst_grid_corner_lat(:,:) = bounds_lat(:,:) ;
//dst_grid_corner_lon(:,:) = bounds_lon(:,:) ;
//
dst_grid_imask [dst_grid_size] =    0 ;
dst_grid_area  [dst_grid_size] = 0.0d ;
dst_grid_frac  [dst_grid_size] = 1.0d ;
dst_grid_imask (:) = 1 - OceMask(0,:,:) ;
dst_grid_imask.int() ;
dst_grid_area  (:) = aire(:,:) ;
dst_grid_frac (:)  = OceFrac(0,:,:) ;
EOF
	cp add_varatm.nco add_varatm_$(basename ${rmpFile} .nc)_o_to_a.nco
	if [[ ${o_to_a} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm_$(basename ${rmpFile} .nc)_o_to_a.nco ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc ${rmpFile}
	    ncks --alphabetize --history --overwrite --variable src_address,dst_address,remap_matrix,src_grid_dims,src_grid_center_lat,src_grid_center_lon,src_grid_corner_lon,src_grid_corner_lat,src_grid_area,src_grid_imask,dst_grid_dims,dst_grid_center_lat,dst_grid_center_lon,dst_grid_area,dst_grid_imask ${rmpFile} rmp_tmp.nc
	    mv rmp_tmp.nc ${rmpFile}
	fi
	
	sed --in-place "s/dst/src/g" add_varatm.nco
	cp add_varatm.nco add_varatm_$(basename ${rmpFile} .nc)_a_to_o.nco
	if [[ ${a_to_o} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm_$(basename ${rmpFile} .nc)_a_to_o.nco ${ATM}_grid_maskFrom_${OCE}_${FMT_OASIS}.nc ${rmpFile}
	    ncks --alphabetize --history --overwrite --variable src_address,dst_address,remap_matrix,src_grid_dims,src_grid_center_lat,src_grid_center_lon,src_grid_area,src_grid_imask,dst_grid_dims,dst_grid_center_lat,dst_grid_center_lon,dst_grid_corner_lon,dst_grid_corner_lat,dst_grid_area,dst_grid_imask ${rmpFile} rmp_tmp.nc
	    mv rmp_tmp.nc ${rmpFile}
	fi
    fi
done
ls -al ${OCE}_coordinates_mask.nc

##
echo ${Titre}"Creates and save auxiliary files for OASIS : grids.nc, areas.nc and masks.nc"${Norm}
## ============================================================================
bash ${SUBMIT_DIR}/CreateOasisGrids.bash --oce ${OCE} --atm ${ATM}



##
echo ${Titre}"Runoff weights"${Norm}
## ===========================================================================
if [[ "X${okRunoff}" = "Xyes" && "${atm}" = "lmd" ]] ; then
    ${PyRun} python3 -u cotes_etal.py --oce=${OCE} --atm=${ATM} \
	      --atmCoastWidth=${atmCoastWidth} --oceCoastWidth=${oceCoastWidth} --searchRadius=${searchRadius} \
	      --grids=grids_${OCE}x${ATM}.nc --areas=areas_${OCE}x${ATM}.nc --masks=masks_${OCE}x${ATM}.nc \
	      --o2a=${ATM}_grid_maskFrom_${OCE}.nc --output=rmp_t${atm}_to_t${oce}_runoff_${FMT_OASIS}.nc \
              --fmt=${FMT_OASIS}
fi

##
echo ${Titre}"Calving weights"${Norm}
## ===========================================================================
if [[ "X${okCalving}" = "Xyes" ]] ; then
    case ${OCE} in
	( eORCA025 )
	cp ${R_IN}/OCE/NEMO/ORCA025_LIM3_PISCES/v3.6_stable/eORCA_R025_runoff_v1.1.nc .
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_full_${FMT_OASIS}.nc     --fmt=${FMT_OASIS} \
		  --oce=${OCE} --atm=${ATM} --type=full     --dir=.
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_nosouth_${FMT_OASIS}.nc  --fmt=${FMT_OASIS} \
		  --oce=${OCE} --atm=${ATM} --type=nosouth  --dir=.  --repartition_file=eORCA_R025_runoff_v1.1.nc
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceberg_${FMT_OASIS}.nc  --fmt=${FMT_OASIS} \
		  --oce=${OCE} --atm=${ATM} --type=iceberg  --dir=.  --repartition_file=eORCA_R025_runoff_v1.1.nc --repartition_var=sornficbisf
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceshelf_${FMT_OASIS}.nc --fmt=${FMT_OASIS} \
		  --oce=${OCE} --atm=${ATM} --type=iceshelf --dir=.  --repartition_file=eORCA_R025_runoff_v1.1.nc --repartition_var=sofwfisf
	;;
	
	( eORCA1.2 )
	cp ${R_IN}/OCE/NEMO/ORCA1_LIM3_PISCES/v3.6_stable/runoff-icb_DaiTrenberth_Depoorter_eORCA1_JD.nc .
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_nosouth_${FMT_OASIS}.nc  --fmt=${FMT_OASIS}\
		  --oce=${OCE} --atm=${ATM} --type=nosouth  --dir=. 
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceberg_${FMT_OASIS}.nc  --fmt=${FMT_OASIS}\
		  --oce=${OCE} --atm=${ATM} --type=iceberg  --dir=. --repartition_file=runoff-icb_DaiTrenberth_Depoorter_eORCA1_JD.nc --repartition_var=Icb_flux
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_iceshelf_${FMT_OASIS}.nc --fmt=${FMT_OASIS}\
		  --oce=${OCE} --atm=${ATM} --type=iceshelf --dir=. --repartition_file=runoff-icb_DaiTrenberth_Depoorter_eORCA1_JD.nc --repartition_var=sornfisf
	;;
	
	( * )
	${PyRun} python3 -u CalvingWeights.py --output=rmp_t${atm}_to_t${oce}_calving_full_${FMT_OASIS}.nc --fmt=${FMT_OASIS} \
		  --oce=${OCE} --atm=${ATM} --type=full     --dir=.
	;;

    esac
fi

##
echo ${Titre}"Save results"${Norm}
## ===========================================================================

cp ${ATM}_grid_maskFrom_${OCE}.nc ${SUBMIT_DIR}
for File in dia_*.nc rmp_*.nc 
do
    ncatted --history --attribute history_of_appended_files,global,d,c,"" ${File}
    [[ "X${Comment}" != "X" ]] && ncatted --history --attribute Comment,global,o,c,"${Comment}"  ${File}
    [[ "X${Version}" != "X" ]] && ncatted --history --attribute Version,global,o,c,"${Version}"  ${File}
    
    NewFile=$(echo ${File} | sed -e "s/${atm}/${ATM}/" -e "s/${oce}/${OCE}/" )
    cp ${File} ${SUBMIT_DIR}/${NewFile}
done

cp areas_${OCE}x${ATM}.nc ${SUBMIT_DIR}
cp grids_${OCE}x${ATM}.nc ${SUBMIT_DIR}
cp masks_${OCE}x${ATM}.nc ${SUBMIT_DIR}


##
echo ${Titre}"Creates a README.txt file"${Norm}
## ===========================================================================
[[ -f README.txt ]] && rm README.txt

cat <<EOF > README.txt
Files produced by CreateWeightsMask.bash and CreateOasisGrids.bash

rmp_* are weights files
dia_* are diagnostic files not needed for the coupler
grids_${OCE}x${ATM}.nc areas_${OCE}x${ATM}.nc masks_${OCE}x${ATM}.nc are auxiliary file needed by OASIS-MCT
All files have the same uuid in the global attributes

Description     : Weigths and auxiliary files for coupling ${OCE} and ${ATM} needed by OASIS-MCT
Conventions     : CF-1.6
source          : IPSL Earth system model
group           : ICMC IPSL Climate Modelling Center
Institution     : IPSL https://www.ipsl.fr
Ocean           : ${OCE} https://www.nemo-ocean.eu
Atmosphere      : ${ATM} http://lmdz.lmd.jussieu.fr
production      : $(finger ${LOGNAME} | head -1 | awk '{print $4, $5}') 
originalFiles   : ${OCE}_coordinates_mask.nc ${ATM}_grid_mask.nc
associatedFiles : grids_${OCE}x${ATM}.nc areas_${OCE}x${ATM}.nc masks_${OCE}x${ATM}.nc
directory       : $(pwd)
timeStamp       : $(date)
uuid            : ${UUID}
HOSTNAME        : $(hostname)
LOGNAME         : $(whoami)
NCO             : NCO netCDF Operator ${NCO} http://nco.sourceforge.net
Python version  : ${PYTHON_VER}
OS              : $(uname -o)
release         : $(uname -r)
hardware        : $(uname -i)
EOF

echo 'SVN Information : ' >> README.txt
echo '$Author$ ' >> README.txt
echo '$Date$ ' >> README.txt
echo '$Revision$ ' >> README.txt
echo '$Id$ ' >> README.txt
echo '$HeadURL$ ' >> README.txt

echo ${Titre}"Compute checksums and add them to README"${Norm}
# -----------------------------------------
cat << EOF >> README.txt
UUID common to all files : ${UUID}

Files produced, with checksum produced by Unix command shasum (version $(shasum --version)) with default algorithm

EOF

for file in *.nc ; do
    echo "$(shasum ${file})" >> README.txt
done

cat <<EOF >> README.txt

================= That's all folk's ! ========================
EOF

cp README.txt ${SUBMIT_DIR}/README_${OCE}x${ATM}.txt

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

