#!/bin/ksh
#
# Name of the grids (4 characters)
srcgrid=torc
tgtgrid=lmdz
# Remapping (done with SEMF in an NCL program see below)
interp_method=bilinear
#interp_method=conserve
#interp_method=patch
#interp_method=neareststod
#
HOMEDIR=/home/evian/coquart/ESMF/ESMF_with_NCL/toy_calcul_weights_with_esmf
RUNDIR=$HOMEDIR/wkdir_esmf_${srcgrid}_${tgtgrid}_${interp_method}
DATADOT=$HOMEDIR/GRIDS_DOT
DATAUND=$HOMEDIR/GRIDS_UNDERSCORE
[ -d $RUNDIR ] || mkdir $RUNDIR
cd $RUNDIR
#
# Modification of the original files for NCL
rename_grids=0
if [ ${rename_grids} == 1 ]; then
    ln -sf $DATADOT/grids_all.nc $RUNDIR/grids.nc
    ln -sf $DATADOT/masks_all.nc $RUNDIR/masks.nc
    ncrename -v ${srcgrid}.lon,${srcgrid}_lon grids.nc
    ncrename -v ${srcgrid}.lat,${srcgrid}_lat grids.nc
    ncrename -v ${srcgrid}.clo,${srcgrid}_clo grids.nc
    ncrename -v ${srcgrid}.cla,${srcgrid}_cla grids.nc
    ncrename -v ${srcgrid}.msk,${srcgrid}_msk masks.nc
#
    ncrename -v ${tgtgrid}.lon,${tgtgrid}_lon grids.nc
    ncrename -v ${tgtgrid}.lat,${tgtgrid}_lat grids.nc
    ncrename -v ${tgtgrid}.clo,${tgtgrid}_clo grids.nc
    ncrename -v ${tgtgrid}.cla,${tgtgrid}_cla grids.nc
    ncrename -v ${tgtgrid}.msk,${tgtgrid}_msk masks.nc
else
    ln -sf $DATAUND/grids_all.nc $RUNDIR/grids.nc
    ln -sf $DATAUND/masks_all.nc $RUNDIR/masks.nc
fi
#
# Remapping using ESMF with NCL
cp $HOMEDIR/interp_esmf_structured_one_step.ncl $RUNDIR/interp_esmf_structured_one_step.ncl
ncl 'interp_method="'${interp_method}'"' 'srcgrid="'${srcgrid}'"' 'tgtgrid="'${tgtgrid}'"' interp_esmf_structured_one_step.ncl

# Change the names of the dimensions in the rmp file created for OASIS3-MCT
ncrename -d n_a,src_grid_size rmp_esmf_for_oa3mct_${srcgrid}to${tgtgrid}_${interp_method}.nc
ncrename -d n_b,dst_grid_size rmp_esmf_for_oa3mct_${srcgrid}to${tgtgrid}_${interp_method}.nc
ncrename -d n_s,num_links rmp_esmf_for_oa3mct_${srcgrid}to${tgtgrid}_${interp_method}.nc
ncrename -d nv_a,src_grid_corners rmp_esmf_for_oa3mct_${srcgrid}to${tgtgrid}_${interp_method}.nc
ncrename -d nv_b,dst_grid_corners rmp_esmf_for_oa3mct_${srcgrid}to${tgtgrid}_${interp_method}.nc
