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

### ===========================================================================
###
### 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$

##
## Configuration
## ===========================================================================

#
# Defines models
# ==============
OCE=ORCA2.3
#OCE=eORCA1.2
#OCE=ORCA025

#ATM=ICO30
#ATM=ICO40
#ATM=ICO450
ATM=LMD9695
#ATM=LMD144X142

#
# Defines OCE grids to handle
# ===========================
ListOCEGRID="T U V"
ListOrder="1st" # " 2nd
ListNormalize="false true"

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

#
# Defines computer
# ================
if [[ $(hostname) = curie* ]] ; then arch=curie ; center=tgcc ; fi
if [[ $(hostname) = irene* ]] ; then arch=irene ; center=tgcc ; fi
PROGRAM=$(basename ${0})

case ${arch} in
    ( curie | irene )
    set +vx
    module purge
    source /ccc/cont003/home/dsm/p86ipsl/.env_intel17.0.2_curie;
    source /ccc/cont003/home/dsm/p86ipsl/.env_netcdf4.3.3.1_curie
    R_IN=$(ccc_home -u igcmg --cccwork)/IGCM
    TMPDIR=${SCRATCHDIR}/TMP
    SUBMIT_DIR=${BRIDGE_MSUB_PWD:-${SUBMIT_DIR}}
    PROGRAM=${BRIDGE_MSUB_REQNAME}
    ;;
    ( * )
    exit -1
    ;;
esac

set -x ; set -e

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

#
# Suffixes
# ---------------------------------------------------------------------------
Listocegrid=${ListOCEGRID,,}

case ${OCE} in
    ( *ORC* )         oce=orc ; oce_domain_type=curvilinear   ;;
esac
case ${ATM} in
    ( *dynamico*    ) atm=ico ; atm_domain_type=unstructured  ;;
    ( *ICO*         ) atm=ico ; atm_domain_type=unstructured  ;;
    ( *lmd* | *LMD* ) atm=lmd ; atm_domain_type=rectilinear   ;;
esac

case ${OCE} in
    ( ORCA2.3*         ) OcePerio=4 ;;
    ( ORCA1* | eORCA1* ) OcePerio=6 ;;
esac
#
# Format for OASIS files : should be NetCDF3 classic or NetCDF3 64 bits
# ---------------------------------------------------------------------------
FL_FMT=64bit


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

##
## NEMO T point towards ATM - 1st order
## ===========================================================================
cp ${R_IN}/OCE/NEMO/${OCE}/${OCE}_coordinates_mask.nc  .
cp ${R_IN}/ATM/GRID/${ATM}_grid.nc .

ln -s ${OCE}_coordinates_mask.nc  oce_grid.nc
ln -s ${ATM}_grid.nc              atm_grid.nc

echo ${Green}"${OCE} T toward ${ATM} - 1storder"${Norm}
cp ${SUBMIT_DIR}/iodef_oce_to_atm.xml   iodef.xml

python 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
python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_src"]'                   -k type  -v ${oce_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_dst"]'                   -k type  -v ${atm_domain_type}
python 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
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]'                               -k name  -v dia_t${oce}_to_t${atm}_1storder_false
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="title"]'       -t "${OCE} mask interpolated to ${ATM}"
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="source_grid"]' -t ${oce_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t ${atm_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="order"]'       -t 1
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_src"]'                    -k type  -v ${oce_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]'                    -k type  -v ${atm_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k weight_filename -v rmp_t${oce}_to_t${atm}_1storder_false.nc
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k order -v 1
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="normalization"]' -t false
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k renormalize -v false

cp iodef.xml iodef_t${oce}_to_t${atm}_1storder_false.xml

time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=no

##
## Correct spurious values (extremes)
## ===========================================================================
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}_1storder_false.nc tmp_dia_t${oce}_to_t${atm}_1storder_false.nc ; mv tmp_dia_t${oce}_to_t${atm}_1storder_false.nc dia_t${oce}_to_t${atm}_1storder_false.nc
ncatted --history -a missing_value,OceFrac,d,,"" -a _FillValue,OceFrac,d,,"" dia_t${oce}_to_t${atm}_1storder_false.nc

##
##  Creates mask on ATM grid
## ===========================================================================
cp dia_t${oce}_to_t${atm}_1storder_false.nc  dia_t${oce}_to_t${atm}_1storder_false_mask.nc
ncks --alphabetize --history --overwrite --variable OceFrac dia_t${oce}_to_t${atm}_1storder_false_mask.nc  ${ATM}_grid_maskFrom_${OCE}.nc
ncks --alphabetize --history --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

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}_1storder_false_mask.nc tmp_dia_t${oce}_to_t${atm}_1storder_false_mask.nc ; mv tmp_dia_t${oce}_to_t${atm}_1storder_false_mask.nc dia_t${oce}_to_t${atm}_1storder_false_mask.nc
ncrename --history --variable OceFrac,OceMask dia_t${oce}_to_t${atm}_1storder_false_mask.nc

ncks --alphabetize --history --append --variable OceMask dia_t${oce}_to_t${atm}_1storder_false_mask.nc   ${ATM}_grid_maskFrom_${OCE}.nc
rm dia_t${oce}_to_t${atm}_1storder_false_mask.nc

##
## Creates mask of coastal OCE points
## ===========================================================================
python ComputeNemoCoast.py  -n ${OcePerio} -i oce_grid.nc

##
## Creates mask of coastal ATM points
## ===========================================================================
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

##
## NEMO, other case, towards ATM 
## ===========================================================================
for order in ${ListOrder} ; do
    case ${order} in
	( 1st ) num_order=1 ;;
	( 2nd ) num_order=2 ;;
    esac
    for normalize in ${ListNormalize} ; do
	for OCEGRID in ${ListOCEGRID} ; do
	    ocegrid=${OCEGRID,,}
	    
	    if [[ ! -f rmp_${ocegrid}${oce}_to_t${atm}_${order}order_${normalize}.nc ]] ; then
		
		echo ${Green}"${OCE} ${OCEGRID} toward ${ATM} - ${order}order - normalize: ${normalize}"${Norm}
		
		python 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_${OCEGRID}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_src"]'                     -k type  -v ${oce_domain_type}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_dst"]'                     -k type  -v ${atm_domain_type}
		python 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_${OCEGRID}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]'                                 -k name  -v dia_${ocegrid}${oce}_to_t${atm}_${order}order_${normalize}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="title"]'         -t "${OCE} mask interpolated to ${ATM}"
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="source_grid"]'   -t ${oce_domain_type}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'     -t ${atm_domain_type}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="order"]'         -t ${num_order}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="normalization"]' -t ${normalize}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_src"]'                      -k type  -v ${oce_domain_type}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]'                      -k type  -v ${atm_domain_type}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k order -v ${num_order}
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k weight_filename -v rmp_${ocegrid}${oce}_to_t${atm}_${order}order_${normalize}.nc
		python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k renormalize     -v ${normalize}
		
		cp iodef.xml iodef_${ocegrid}${oce}_t${atm}_${order}order_${normalize}.xml
		
		time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes
	    fi
	    
	done
    done
done

##
## ATM towards NEMO points
## ===========================================================================
cp ${SUBMIT_DIR}/iodef_atm_to_oce.xml           iodef.xml

python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_src"]'                   -k type  -v ${atm_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_dst"]'                   -k type  -v ${oce_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="title"]'       -t "${ATM} mask interpolated to ${OCE}"
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="source_grid"]' -t ${atm_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t ${oce_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_src"]'                    -k type  -v ${atm_domain_type}
python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]'                    -k type  -v ${oce_domain_type}
	    
for order in ${ListOrder} ; do
    case ${order} in
	( 1st ) num_order=1 ;;
	( 2nd ) num_order=2 ;;
    esac
    for normalize in ${ListNormalize} ; do
	python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k order -v ${num_order}
	python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="order"]'         -t ${num_order}   
    	python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="normalization"]' -t ${normalize}
	python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain'   -k renormalize     -v ${normalize}
	
	for OCEGRID in ${ListOCEGRID} ; do
	    ocegrid=${OCEGRID,,}
	    
	    echo ${Green}"${ATM} toward ${OCE} ${OCEGRID} - ${order}order - normalize: ${normalize}"${Norm}
	    python 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_${OCEGRID}
	    python 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_${OCEGRID}
	    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]'                               -k name  -v dia_t${atm}_to_${ocegrid}${oce}_${order}order_${normalize}
	    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k weight_filename -v rmp_t${atm}_to_${ocegrid}${oce}_${order}order_${normalize}.nc
	    cp iodef.xml iodef_t${atm}_to_${ocegrid}${oce}_${order}order_${normalize}.xml
	    
	    time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes
	    
	done
    done
done

##
## ATM towards NEMO points - runoff
## ===========================================================================
cp ${SUBMIT_DIR}/iodef_atm_to_oce.xml           iodef.xml
for normalize in ${ListNormalize} ; do
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_src"]'                   -k type  -v ${atm_domain_type}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/domain_definition/domain[@id="domain_dst"]'                   -k type  -v ${oce_domain_type}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="title"]'       -t "${ATM} coastal mask interpolated to ${OCE}"
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="source_grid"]' -t ${atm_domain_type}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t ${oce_domain_type}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_src"]'                    -k type  -v ${atm_domain_type}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]'                    -k type  -v ${oce_domain_type}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k order -v 1
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="order"]'       -t 1
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="normalization"]' -t ${normalize}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_src"]'                         -k name  -v ${ATM}_grid_maskFrom_${OCE}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_src"]/field[@id="mask_src"]'   -k name  -v AtmCoastal
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_read"]/file_definition/file[@id="file_dst"]/field[@id="mask_dst"]'   -k name  -v OceCoastal
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]'                               -k name  -v dia_c${atm}_to_t${oce}_1storder_${normalize}
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k weight_filename -v rmp_c${atm}_to_t${oce}_1storder_${normalize}.nc
    python update_xml.py -i iodef.xml -n 'context[@id="interpol_run"]/domain_definition/domain[@id="domain_dst"]/interpolate_domain' -k renormalize     -v ${normalize}
    
    cp iodef.xml iodef_c${atm}_to_t${oce}_1storder_${normalize}.xml
    
    time /usr/bin/time ccc_mprun ./interpol.exe --mask_src=yes --mask_dst=yes
done
##
## Change all NetCDF files to NetCDF 3 format (needed for OASIS)
## ===========================================================================
for InFile in *.nc ; do
    mv ${InFile} tmp_${InFile}
    ncks --alphabetize --fl_fmt=${FL_FMT} --history  tmp_${InFile}  ${InFile}
done

##
## Add time axis and coordinates information
## (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

if [[ ${atm} = ico ]] ; then
    cat <<EOF > add_time.nco
OceFrac    [time_counter,cell] = OceFrac    (:) ;
OceMask    [time_counter,cell] = OceMask    (:) ;
AtmCoastal [time_counter,cell] = AtmCoastal (:) ;
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,c,c,"time_counter cell"    \
            -a coordinates,OceMask,c,c,"time_counter cell"    \
            -a coordinates,AtmCoastal,c,c,"time_counter cell" \
	    -a coordinates,aire,c,c,"cell" \
            ${ATM}_grid_maskFrom_${OCE}.nc
fi
if [[ ${atm} = lmd ]] ; then
    cat <<EOF > add_time.nco
OceFrac    [time_counter,lat,lon] = OceFrac    (:,:) ;
OceMask    [time_counter,lat,lon] = OceMask    (:,:) ;
AtmCoastal [time_counter,lat,lon] = AtmCoastal (:,:) ;
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,c,c,"time_counter lat lon"    \
            -a coordinates,OceMask,c,c,"time_counter lat lon"    \
            -a coordinates,AtmCoastal,c,c,"time_counter lat lon" \
            -a coordinates,aire,c,c,"lat lon" \
            ${ATM}_grid_maskFrom_${OCE}.nc
fi
ncks --alphabetize --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


##
## Add some metadata in file headers
## ===========================================================================

UUID=$(uuid)
NCO="$(ncks --version |& tail -1|sed 's/ncks //')"
PYTHON_VER=$( python -i -c "import sys ; print (sys.version.split(' ')[0])" )
for InFile in *${oce}_to_*${atm}_*.nc *${atm}_to_*${oce}_*.nc ${ATM}_grid_maskFrom_${OCE}.nc ; 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,"Python version ${PYTHON_VER}"          \
	    --attribute OS,global,o,c,"$(uname -o)"                               \
	    --attribute release,global,o,c,"$(uname -r)"                          \
	    --attribute hardware,global,o,c,"$(uname -i)"                         \
	    --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 Comment,global,o,c,"Preliminary attempt - Do not trust !" \
	    --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


##
## Update and complete weights file to fit OASIS requested format
## ===========================================================================
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=${FL_FMT} --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_*.nc ) ncatted --history --attribute map_method,global,o,c,"Conservative Remapping - 1st order"  ${rmpFile} ;;
	( *_2ndorder_*.nc ) ncatted --history --attribute map_method,global,o,c,"Conservative Remapping - 2nd order"  ${rmpFile} ;;
    esac
    case ${rmpFile} in
	( *_true.nc  ) ncatted --history --attribute map_method,global,o,c,"Normalization: true"  ${rmpFile} ;;
	( *_false.nc ) ncatted --history --attribute map_method,global,o,c,"Normalization: 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,"${oce_domain_type}" \
		--attribute dest_grid,global,o,c,"${atm_domain_type}"   \
		${rmpFile}	
	;;
	( rmp_*${atm}_to_*${oce}_* )
	ncatted --history \
		--attribute title,global,o,c,"Weights ${ATM} to ${OCE}" \
		--attribute source_grid,global,o,c,"${atm_domain_type}" \
		--attribute dest_grid,global,o,c,"${oce_domain_type}"   \
		${rmpFile}
	;;
    esac
done

##
## Add missing variables in rmp files
## ===========================================================================
for rmpFile in rmp_* ; do
    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 c ; do # Identify grids
	case ${rmpFile} in
	    (  rmp_${Grid}${oce}_to_?${atm}_*.nc ) ogrid=${Grid} ;;
	    (  rmp_?${oce}_to_${Grid}${atm}_*.nc ) agrid=${Grid} ;;
	    (  rmp_${Grid}${atm}_to_?${oce}_*.nc ) agrid=${Grid} ;;
	    (  rmp_?${atm}_to_${Grid}${oce}_*.nc ) ogrid=${Grid} ;;
	esac
    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

    [[ ${o_to_a} = true ]] && ncap2 --history --append --script-file add_varoce.nco oce_grid.nc ${rmpFile}
    sed --in-place "s/src_/dst_/g" add_varoce.nco
    [[ ${a_to_o} = true ]] && ncap2 --history --append --script-file add_varoce.nco oce_grid.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(:) ;
EOF
	if [[ ${o_to_a} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm.nco ${ATM}_grid_maskFrom_${OCE}.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
	if [[ ${a_to_o} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm.nco ${ATM}_grid_maskFrom_${OCE}.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
	if [[ ${o_to_a} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm.nco ${ATM}_grid_maskFrom_${OCE}.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
	if [[ ${a_to_o} = true ]] ; then
	    ncap2 --history --append --script-file add_varatm.nco ${ATM}_grid_maskFrom_${OCE}.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

##
## Save results
## ===========================================================================
cp ${ATM}_grid_maskFrom_${OCE}.nc ${SUBMIT_DIR}
for File in dia_*.nc rmp_*.nc
do
    NewFile=$(echo ${File} | sed -e "s/${atm}/${ATM}/" -e "s/${oce}/${OCE}/" )
    cp ${File} ${SUBMIT_DIR}/${NewFile}
done

##
## Creates and save auxiliary files for OASIS
## ===========================================================================
bash ${SUBMIT_DIR}/CreateOasisGrids.bash --oce ${OCE} --atm ${ATM}

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


## ===========================================================================
##
##                               That's all folk's !!!
##
## ===========================================================================

